diff --git a/README.md b/README.md index 5e80075..63ac76c 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ This script bootstraps the existing Chosen plugin without making any modificatio ## How to Use -This plugin exposes a new jQuery function named `ajaxChosen` that we call on a `select` element. The first argument are the options passed to the jQuery $.ajax function. The `data` parameter should be omitted, and the `success` callback is optional. +This plugin exposes a new jQuery function named `ajaxChosen` that we call on a `select` element. The first argument are the options passed to the jQuery $.ajax function. The `data` parameter can be used to send parameters to the service, except `term` that is used to send the search string, and the `success` callback is optional. The second argument is a callback that tells the plugin what HTML `option` elements to make. It is passed the data returned from the ajax call, and you have to return an object where the key is the HTML `option` value attribute and the value is the text to display. In other words: @@ -22,6 +22,7 @@ becomes: $("#example-input").ajaxChosen({ method: 'GET', url: '/ajax-chosen/data.php', + data: { user_id: 23 }, dataType: 'json' }, function (data) { var terms = {}; diff --git a/lib/ajax-chosen.js b/lib/ajax-chosen.js index 1035239..ec21421 100644 --- a/lib/ajax-chosen.js +++ b/lib/ajax-chosen.js @@ -12,9 +12,8 @@ if (this.timer) clearTimeout(this.timer); $(this).data('prevVal', val); field = $(this); - options.data = { - term: val - }; + options.data = options.data || {}; + options.data.term = val; if (typeof success === "undefined" || success === null) { success = options.success; } @@ -41,9 +40,8 @@ val = $.trim($(this).attr('value')); if (val.length < 3 || val === $(this).data('prevVal')) return false; field = $(this); - options.data = { - term: val - }; + options.data = options.data || {}; + options.data.term = val; if (typeof success === "undefined" || success === null) { success = options.success; } @@ -68,4 +66,4 @@ }; })(jQuery); -}).call(this); +}).call(this); \ No newline at end of file diff --git a/src/ajax-chosen.coffee b/src/ajax-chosen.coffee index 04109cf..ec82ddf 100644 --- a/src/ajax-chosen.coffee +++ b/src/ajax-chosen.coffee @@ -38,7 +38,8 @@ # I'm assuming that it's ok to use the parameter name `term` to send # the form value during the ajax call. Change if absolutely needed. - options.data = term: val + options.data = options.data || {} + options.data.term = val # If the user provided an ajax success callback, store it so we can # call it after our bootstrapping is finished. @@ -91,7 +92,8 @@ val = $.trim $(this).attr('value') return false if val.length < 3 or val is $(this).data('prevVal') field = $(this) - options.data = term: val + options.data = options.data || {} + options.data.term = val success ?= options.success options.success = (data) -> return if not data?