jQueryUI Autocomplete value different than label
Asked Answered
N

1

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"}]
Nellnella answered 30/4, 2013 at 20:35 Comment(1)
possible duplicate of Autocomplete applying value not label to textboxOsteal
M
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
});
Metamerism answered 30/4, 2013 at 20:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.