Reputation: 1172
I am replacing the jQuery-ui Autocomplete library with one that I made. The old initializer for my input element looks like this:
$('#search_input').autocomplete({
minLength: 2,
select: function(event, ui) {
$('.some_element').val('ui.item.id');
return false;
}
});
My new auto-complete library looks like this:
$.fn.custom_search = function() {
$(this).on('keydown click', (e) function(){
switch e.type {
case 'keydown':
...
search_term = $(this).val();
ajax_caller(search_term);
break;
case 'click'
...
break;
}
};
How can I maintain the 'select' functionality from the jQuery-ui Autocomplete? I want everything passed to select in the initializer to fire upon an item being selected from the search results from my custom auto-complete.
The 'ajax_caller' function passes the search term to the controller. The controller compiles a list and returns it to a js.erb which creates a list of search term results and attaches it to the bottom of the input.
The select callback is supposed to be fired when someone chooses an option from the search term results.
Upvotes: 0
Views: 82
Reputation: 16172
You need to pass the select
callback as an option into your plugin, something like this:
$.fn.custom_search = function(options) {
options = options || {};
var select = options.select || function() {};
$(this).on('keydown click', (e) function(){
switch e.type {
case 'keydown':
...
search_term = $(this).val();
select($(this), search_term);
...
}
};
And then you will pass it like for jQuery autocomplete:
$('#search_input').custom_search({
select: function(element, value) {
$('.some_element').val('ui.item.id');
return false;
}
});
Also check this jQuery plugin template, and you can find more similar templates to help you writing a well-structured plugin.
Upvotes: 1