Skip to content

Commit 1a734e9

Browse files
committed
Adding support for multiple values triggered by a separator option
1 parent 49f8c1c commit 1a734e9

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

ui/jquery.ui.autocomplete.js

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@
1717
$.widget( "ui.autocomplete", {
1818
options: {
1919
minLength: 1,
20-
delay: 300
20+
delay: 300,
21+
separator: false
2122
},
2223
_create: function() {
2324
var self = this,
@@ -108,14 +109,14 @@ $.widget( "ui.autocomplete", {
108109
if ( false !== self._trigger( "focus", null, { item: item } ) ) {
109110
// use value to match what will end up in the input, if it was a key event
110111
if ( /^key/.test(event.originalEvent.type) ) {
111-
self.element.val( item.value );
112+
self.element.val( self.options.separator ? self._insertValue(item.value) : item.value );
112113
}
113114
}
114115
},
115116
selected: function( event, ui ) {
116117
var item = ui.item.data( "item.autocomplete" );
117118
if ( false !== self._trigger( "select", event, { item: item } ) ) {
118-
self.element.val( item.value );
119+
self.element.val( self.options.separator ? self._insertValue(item.value) : item.value );
119120
}
120121
self.close( event );
121122
// only trigger when focus was lost (click on menu)
@@ -198,7 +199,35 @@ $.widget( "ui.autocomplete", {
198199
// always save the actual value, not the one passed as an argument
199200
.val();
200201

201-
this.source( { term: value }, this.response );
202+
if( this.options.separator ){
203+
value = this._getValue( value );
204+
}
205+
if( value ){
206+
this.source( { term: value }, this.response );
207+
}
208+
},
209+
210+
_getValue: function( value ){
211+
this.caretPos = this.element[0].selectionStart;
212+
var begin = value.substr( 0, this.caretPos ).split( this.options.separator ),
213+
end = value.substr( this.caretPos ).split( this.options.separator );
214+
return begin[ begin.length-1 ] + end[0];
215+
},
216+
217+
_insertValue: function( value ){
218+
var begin = this.term.substr( 0, this.caretPos ).split( this.options.separator ),
219+
end = this.term.substr( this.caretPos ).split( this.options.separator ),
220+
result = '';
221+
begin.pop();
222+
end.shift();
223+
if(begin.length){
224+
result = begin.join( this.options.separator ) + this.options.separator;
225+
}
226+
result += value;
227+
if(end.length){
228+
result += this.options.separator + end.join( this.options.separator );
229+
}
230+
return result;
202231
},
203232

204233
_response: function( content ) {

0 commit comments

Comments
 (0)