From 5af8799d1f795f0453634ef5f6529fff5653bea1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E4=B8=96=E9=BE=99?= Date: Mon, 15 Aug 2016 22:38:51 +0800 Subject: [PATCH] add onChange callback function to fix onSelect and onChange conflicting --- readme.md | 16 ++++++++++++++++ src/jquery.autocomplete.js | 3 ++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/readme.md b/readme.md index a5c54df..810dc44 100644 --- a/readme.md +++ b/readme.md @@ -36,6 +36,7 @@ The standard jquery.autocomplete.js file is around 13KB when minified. * `transformResult`: `function(response, originalQuery) {}` called after the result of the query is ready. Converts the result into response.suggestions format. * `onSelect`: `function (suggestion) {}` Callback function invoked when user selects suggestion from the list. `this` inside callback refers to input HtmlElement. +* `onChange`: `function (value) {}` Callback function invoked when on change event. * `minChars`: Minimum number of characters required to trigger autosuggest. Default: `1`. * `lookupLimit`: Number of maximum results to display for local lookup. Default: no limit. * `lookup`: Callback function or lookup array for the suggestions. It may be array of strings or `suggestion` object literals. @@ -151,6 +152,21 @@ $('#autocomplete').autocomplete({ }); ``` +Use onChange: + +```javascript +$('#autocomplete').autocomplete({ + serviceUrl: '/autocomplete/countries', + onSelect: function (suggestion) { + alert('You selected: ' + suggestion.value + ', ' + suggestion.data); + }, + onChange: function (value) { + console.log(value); + } +}); + +``` + ##Styling Generated HTML markup for suggestions is displayed below. You may style it any way you'd like. diff --git a/src/jquery.autocomplete.js b/src/jquery.autocomplete.js index 17146d2..3f77d02 100644 --- a/src/jquery.autocomplete.js +++ b/src/jquery.autocomplete.js @@ -208,7 +208,7 @@ that.el.on('keyup.autocomplete', function (e) { that.onKeyUp(e); }); that.el.on('blur.autocomplete', function () { that.onBlur(); }); that.el.on('focus.autocomplete', function () { that.onFocus(); }); - that.el.on('change.autocomplete', function (e) { that.onKeyUp(e); }); + that.el.on('change.autocomplete', function (e) { $(that).data("_change.autocomplete", setTimeout(function () { if ($.isFunction(that.options.onChange)) { that.options.onChange(that.el.val()); } }, 500)) }); that.el.on('input.autocomplete', function (e) { that.onKeyUp(e); }); }, @@ -913,6 +913,7 @@ }, onSelect: function (index) { + clearTimeout($(this).data("_change.autocomplete")); var that = this, onSelectCallback = that.options.onSelect, suggestion = that.suggestions[index];