jQuery-UI multicomplete widget (based on autocomplete)
Posted: July 11th, 2010 | Author: shesek | Filed under: Javascript, jQuery, Web Development | Tags: Autocomplete, jQuery, jQuery UI, jquery widget, multicomplete, Multiple Autocomplete | 5 Comments »After writing my $.fn.autocomplete function to allow using jQuery’s UI autocomplete with multiple selections, I’ve rewritten it as a widget that extends the autocomplete widget. Basically, it works the exact same as autocomplete – other than allowing to select multiple values separated with a comma.
A few things were improved/changed in that version:
- All options are settable, including all the callbacks that I’m modifying. your callbacks will be called first, and returning false from them will have effect.
- All methods/getters/setters are available via multicomplete() (e.g. $(..).multicomplete(‘option’, ‘source’, ['foo', 'bar'])). When using multicomplete, setting/getting them via .autocomplete() will no longer work.
- Events are prefixed with multicomplete instead of autocomplete (e.g. $(..).bind(‘multicompletesearch’, function(){…})). Using “autocomplete” as the prefix won’t work.
- When you pass an array as the source, items that were already selected won’t show up in the autocomplete list.
- When you pass a URL as the source, a new parameter named “selected” is passed in the AJAX request so your server-side code can know which items are already selected and not return them.
It should be noted that most of the handling is still done with jQuery-UI’s autocomplete, my multicomplete code just extends that widget and changes a few things. Everything should work as expected, and I don’t foresee any issues when new versions of jQuery UI are out – unless they make radical changes.
So here’s the demo (only works on the single post page):
Source code of demo:
$('#suggest').multicomplete({
source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby", "python", "c", "scala", "groovy", "haskell", "perl"]
});
Source code of the multicomplete widget:
(function($ ,$a, $p){ // getting $p as a parameter doesn't require me to "var $p=..." and saves a two bytes
("var " versus ",x" in argument list [when minifier is shrinking variables])
$p=$a.prototype;
$.widget('ui.multicomplete', $a, {
// Search for everything after the last "," instead of the whole input contents
_search: function(value){
$p._search.call(this, value.match(/s*([^,]*)s*$/)[1]);
},
// Overwrite _trigger to make custom handling for events while still allowing user callbacks
// Setting my own callbacks on this.options or binding using .bind() doesn't allow me to properly handle user callbacks, as this must be called AFTER the user callbacks are executed (which isn't possible by bind()ing when this.options[] is set)
_trigger: function(type, event, data) {
// call "real" triggers
var ret = $p._trigger.apply(this, arguments);
// When its select event, and user callback didn't return FALSE, do my handling and return false
if (type == 'select' && ret !== false) {
// When a selection is made, replace everything after the last "," with the selection instead of replacing everything
var val=this.element.val();
this.element.val(val.replace(/[^,]+$/,(val.indexOf(',') != -1 ?' ':'')+data.item.value + ', '));
ret = false;
}
// Force false when its the focus event - parent should never set the value on focus
return (type == 'focus' ? false : ret);
},
_create:function(){
var self=this;
// When menu item is selected and TAB is pressed focus should remain on current element to allow adding more values
this.element.keydown(function(e){
self.menu.active && e.keyCode == $.ui.keyCode.TAB && e.preventDefault();
});
$p._create.call(this);
},
_initSource: function() {
// Change the way arrays are handled by making autocomplete think the user sent his own source callback instead of an array
// The way autocomplete is written doesn't allow me to do it in a prettier way
if ( $.isArray(this.options.source) ) {
var array = this.options.source, self = this;
this.options.source = function( request, response ) {
response( self.filter(array, request) ); // Use our filter() and pass the entire request object so the filter can tell what's currently selected
};
}
// call autocomplete._initSource to create this.source function according to user input
$p._initSource.call(this);
// Save a copy of current source() function, than new source() sets request.selected and delegate to original source
var _source = this.source;
this.source = function(request, response) {
request.selected = this.element.val().split(/s*,s*/);
request.selected.pop(); // don't include the term the user is currently writing as selected
_source(request, response);
};
// TODO: instead of overwritting this.source, I can overwrite _search which is easier, but than I'll have to repeat jQuery-UI's code that might change
},
// Like $.ui.autocomplete.filter, but excludes items that are already selected
filter: function(array, request) {
return $.grep($a.filter(array, request.term),function(value){return $.inArray(value, request.selected) == -1;});
}
});
})(jQuery, jQuery.ui.autocomplete);
Minified:
(function($,f,g){g=f.prototype;$.widget(‘ui.multicomplete’,f,{_search:function(a){g._search.call(this,a.match(/s*([^,]*)s*$/)[1])},_trigger:function(a,b,c){var d=g._trigger.apply(this,arguments);if(a==’select’&&d!==false){var e=this.element.val();this.element.val(e.replace(/[^,]+$/,(e.indexOf(‘,’)!=-1?’ ‘:”)+c.item.value+’, ‘));d=false}return(a==’focus’?false:d)},_create:function(){var a=this;this.element.keydown(function(e){a.menu.active&&e.keyCode==$.ui.keyCode.TAB&&e.preventDefault()});g._create.call(this)}, _initSource:function(){if($.isArray(this.options.source)){var c=this.options.source,self=this;this.options.source=function(a,b){b(self.filter(c,a))}}g._initSource.call(this);var d=this.source;this.source=function(a,b){a.selected=this.element.val().split(/s*,s*/);a.selected.pop();d(a,b)}},filter:function(b,c){return $.grep(f.filter(b,c.term),function(a){return $.inArray(a,c.selected)==-1})}})})(jQuery,jQuery.ui.autocomplete);
Download: Full code with comments (3141 bytes) or Minified code (932 bytes)
Released under the MIT and GPL licenses.
P.S. I would like to thank ajpiano from #jquery (at freenode) for suggesting me to write this as a widget. I’ve learned a few things on jQuery/jQuery-UI in the process and I’ll definitely start writing some of my code as widgets, I really like the way they works.