jQuery UI autocomplete with item and id

前端 未结 11 1813
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 00:32

I have the following script which works with a 1 dimensional array. Is it possible to get this to work with a 2 dimensional array? Then whichever item is selected, by clic

11条回答
  •  孤独总比滥情好
    2020-11-29 00:40

    Just want to share what worked on my end, in case it would be able to help someone else too. Alternatively based on Paty Lustosa's answer above, please allow me to add another approach derived from this site where he used an ajax approach for the source method

    http://salman-w.blogspot.ca/2013/12/jquery-ui-autocomplete-examples.html#example-3

    The kicker is the resulting "string" or json format from your php script (listing.php below) that derives the result set to be shown in the autocomplete field should follow something like this:

        {"list":[
         {"value": 1, "label": "abc"},
         {"value": 2, "label": "def"},
         {"value": 3, "label": "ghi"}
        ]}
    

    Then on the source portion of the autocomplete method:

        source: function(request, response) {
            $.getJSON("listing.php", {
                term: request.term
            }, function(data) {                     
                var array = data.error ? [] : $.map(data.list, function(m) {
                    return {
                        label: m.label,
                        value: m.value
                    };
                });
                response(array);
            });
        },
        select: function (event, ui) {
            $("#autocomplete_field").val(ui.item.label); // display the selected text
            $("#field_id").val(ui.item.value); // save selected id to hidden input
            return false;
        }
    

    Hope this helps... all the best!

提交回复
热议问题