I am trying to set up jQuery autocomplete in Rails 3.2.0. I have it working fine if I set up an array in javascript as the data source. My problem is that the search terms will eventually become too many to load during page load. I am trying to get the remote data source set up but it is failing to populate the content on the page.
The data is being returned, but the selections are not populating. The vast majority of this code is straight from the jQuery UI demos site.
What am I missing?
$( "#tags" )
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "get/tags", {
term: extractLast( request.term )
}, response.name );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
I found my problem. Silly me. Reading ALL the documentation on the autocomplete plugin is helpful. My problem was that I was not providing a proper “termed” JSON array.
Quoted from the jQuery UI page
An Array of Objects with label and value properties:
[ { label: “Choice1”, value: “value1” }, … ]
So creating the rendered JSON in your Rails app like this:
Also in my code above the $.getJSON should be defined like so: