I have a jQuery UI Autocomplete
that works fine, if the returned json
object looks like this:
label:name
value:name
Then it searches through myname and when the user selects one, it populates the input box with myname.
But what I want is for the json object to look like this:
label:name
value:id
When I do this, the autocomplete populates the input box with the id number instead of the name string.
How can I have the autocomplete set the displayed text to the name, and the hidden value to the value?
I don't see any way to do this in the official docs.
Here's my autocomplete:
$("#eventAccount").autocomplete({
minLength: 2,
source: function (request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
request.e = "getMyAccountAutocomplete";
$.getJSON("/admin/ajaxController.php", request, function (data, status, xhr) {
cache[term] = data;
response(data);
});
}
});
And the JSON it's getting back:
[{"label":"My fancy name","value":"229"}]
There's no built in way to do this. Instead, you should override the select
event, and update the input
value yourself;
$("#eventAccount").on("autocompleteselect", function (e, ui) {
e.preventDefault(); // prevent the "value" being written back after we've done our own changes
this.value = ui.item.label;
// Put ui.item.value somewhere
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With