16

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"}]
Sachin
  • 40,216
  • 7
  • 90
  • 102
Lurk21
  • 2,307
  • 12
  • 37
  • 55
  • 1
    possible duplicate of [Autocomplete applying value not label to textbox](http://stackoverflow.com/questions/7642855/autocomplete-applying-value-not-label-to-textbox) – Andrew Whitaker Apr 30 '13 at 20:38

1 Answers1

11

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
});
Matt
  • 74,352
  • 26
  • 153
  • 180