Lurk21 Lurk21 - 1 year ago 60
jQuery Question

jQueryUI Autocomplete value different than label

I have a

jQuery UI Autocomplete
that works fine, if the returned
object looks like this:


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:


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:

minLength: 2,
source: function (request, response) {
var term = request.term;
if (term in cache) {

request.e = "getMyAccountAutocomplete";

$.getJSON("/admin/ajaxController.php", request, function (data, status, xhr) {
cache[term] = data;

And the JSON it's getting back:

[{"label":"My fancy name","value":"229"}]

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download