Fuente: http://www.jensbits.com/2011/08/24/using-jquery-autocomplete-when-remote-source-json-does-not-contain-label-or-value-fields/
Using jQuery Autocomplete When Remote Source JSON Does Not Contain ‘Label’ or ‘Value’ Fields
If the jQuery autocomplete plugin uses a remote datasource, the autocomplete expects it to return json data with a ‘label’ and/or a ‘value’ field. If you return one, either ‘label’ or ‘value’, the autocomplete uses it for both the suggestion menu and the value of the input box. If you return both, it uses the ‘label’ for the suggestion menu and the ‘value’ for the value of the input box.
What happens when the remote source returns neither a ‘label’ or ‘value’ and you cannot change the returned json of the remote source? Or, better yet, it does return them but you want different values used in the autocomplete?
For example, the remote source json string below has neither a ‘label’ or a ‘value’ field. Using this would result in the autocomplete not functioning at all.
[{"id":"3","state":"Alaska","abbrev":"AK"},{"id":"4","state":"Alabama","abbrev":"AL"},{"id":"9","state":"California","abbrev":"CA"}] |
You can work around this by modifying the ‘source’ option of the autocomplete to assign one or both of the ‘label’ and ‘value’ fields values found in the json result.
To modify the ‘source’ option of the autocomplete, we add an ajax call to the source and, in the ‘success’ callback, we assign the values of all the variables we want the autocomplete to use.
$("#state").autocomplete({ |
source: function( request, response ) { |
url: "states_remote.php", |
data: {term: request.term}, |
success: function(data) { |
response($.map(data, function(item) { |
select: function(event, ui) { |
$('#state_id').val(ui.item.id); |
$('#abbrev').val(ui.item.abbrev); |
To break this down, the ajax function has the following options:
- url: url of page that returns the json; subject to same origin policy (you should use jsonp for cross-domain url’s)
- dataType: sets the data coming back to the ajax function as json
- data: sets the query parameter of ‘term’ to the value of ‘request.term’ which is what the user types into the input box
- success: callback function that maps the returned json and sets the variables that the autcomplete will use
In this example, the ‘select’ option of the autocomplete sets the label field used by the autocomplete in the suggest menu and as the value of the input box. It also sets the values of some additional fields in the form. They are returned to the page in the demo to verify that they are set. ‘id’ is a hidden field in the form and ‘abbrev’ populates a read-only input box in the form.
And, if the json result does set the ‘label’ and/or ‘value’ fields but you don’t want those values in the autocomplete, you can adjust the ‘return’ of the ‘success’ function in th ‘ajax’ call:
Remember, the autocomplete needs a ‘label’ or ‘value’. Don’t forget to set one, the other, or both.