jQuery UI autocomplete with JSON

后端 未结 3 1259
旧时难觅i
旧时难觅i 2020-11-27 04:06

Alright been racking my brain on this (im terrible at this) but yea ive tried reading all i can and still cant get it to work.

trying to do autocomplete with jquery

3条回答
  •  情歌与酒
    2020-11-27 04:51

    You need to transform the object you are getting back into an array in the format that jQueryUI expects.

    You can use $.map to transform the dealers object into that array.

    $('#dealerName').autocomplete({
        source: function (request, response) {
            $.getJSON("/example/location/example.json?term=" + request.term, function (data) {
                response($.map(data.dealers, function (value, key) {
                    return {
                        label: value,
                        value: key
                    };
                }));
            });
        },
        minLength: 2,
        delay: 100
    });
    

    Note that when you select an item, the "key" will be placed in the text box. You can change this by tweaking the label and value properties that $.map's callback function return.

    Alternatively, if you have access to the server-side code that is generating the JSON, you could change the way the data is returned. As long as the data:

    • Is an array of objects that have a label property, a value property, or both, or
    • Is a simple array of strings

    In other words, if you can format the data like this:

    [{ value: "1463", label: "dealer 5"}, { value: "269", label: "dealer 6" }]
    

    or this:

    ["dealer 5", "dealer 6"]
    

    Then your JavaScript becomes much simpler:

    $('#dealerName').autocomplete({
        source: "/example/location/example.json"
    });
    

提交回复
热议问题