Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQueryUI Autocomplete value different than label

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"}]
like image 721
Lurk21 Avatar asked Apr 30 '13 20:04

Lurk21


1 Answers

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
});
like image 97
Matt Avatar answered Oct 08 '22 10:10

Matt