Skip to content

Instantly share code, notes, and snippets.

@jaimeiniesta
Created August 12, 2011 15:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jaimeiniesta/1142315 to your computer and use it in GitHub Desktop.
Save jaimeiniesta/1142315 to your computer and use it in GitHub Desktop.
jQuery-UI autocomplete with multiple comma-separated values from a JSON remote source
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#new_interest" ).autocomplete({
source: function( request, response ) {
$.getJSON( "/tags.json", {
term: extractLast( request.term )
}, response );
},
select: function( event, ui ) {
// Add the selected term appending to the current values with a comma
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// join all terms with a comma
this.value = terms.join( ", " );
return false;
},
focus: function() {
// prevent value inserted on focus when navigating the drop down list
return false;
}
});
});
[{
"id": 28,
"name": "sex",
"value": "sex"
}, {
"id": 29,
"name": "drugs",
"value": "drugs"
}, {
"id": 30,
"name": "rock and roll",
"value": "rock and roll"
}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment