jquery ui autocomplete stack overflow style
I am interested in building a stack overflow style tags input using jquery autocomplete.
So the main operations are:
- If you type 'a', queries with 'a开发者_JAVA百科' will show up (no problem, that's how jquery autocomplete works)
- If you press down or up to select a recommendation, the input box gets changed.
The trick here is that whenever the input is changed, only the last item is changed.
This means that if you take the value of the input, and select a query, only
var l = $input.val().split(' ');
l[l.length-1] will be changed
I tried monkeypatching jquery autocomplete's _value function, but to no success. I realized that even when you move up or down or esc, the input gets messed up as well. I am begging for someone who is experienced in this autocomplete to shed me some light on this
Anyway I have managed to understand the source code and fix my problem.
Basically monkeypatching jquery.autocomplete's _value function will do.
(function( $, undefined ) {
/* This is the getter and setter of the value
* When getting, parse and return the last part
* When setting, just set the last part
*/
jQuery.ui.autocomplete.prototype._value = function( value ) {
var originalstr = this.valueMethod.apply( this.element);
if (arguments.length) {
var l = originalstr.split(' ');
l[l.length -1] = arguments[0];
this.valueMethod.apply(this.element, [l.join(' ')]);
}
else {
var l = originalstr.split(' ');
return l[l.length -1];
}
};
} ( jQuery ));
This code modifies the way autocomplete get and sets the value inside the input box
精彩评论