开发者

jQuery UI Autocomplete how to implement Must Match in existing setup?

开发者 https://www.devze.com 2023-03-16 16:37 出处:网络
I have the following code and am curious as how to force the input to match the contents of the autocomplete:

I have the following code and am curious as how to force the input to match the contents of the autocomplete:

$("#foo").autocomplete({
    source: function( request, response ) {
        $.ajax({
            url: "index.pl",
            dataType: "json",
  开发者_Python百科          data: {
                type: 'foo',
                term: request.term
            },
            success: function( data ) {
                response( $.map( data.items, function( item ) {
                    return {
                        value: item.id
                    }
                }));
            }
        });
    },
    minLength: 1
});


Answering this question for the benefit of anyone who stumbles upon this problem in 2013(yeah right!)

$("#my_input").autocomplete({
    source: '/get_data/',
    change: function(event, ui) {
        var source = $(this).val();
            var temp = $(".ui-autocomplete li").map(function () { return $(this).text()}).get();
        var found = $.inArray(source, temp);

        if(found < 0) {
            $(this).val(''); //this clears out the field if non-existing value in <select><options> is typed.
        }
    }
});

Explanation: The map() method creates a jQuery object populated with whatever is returned from the function (in this case, the text content of each <li> element).

The get() method (when passed no argument) converts that jQuery object into an actual Array.

Here is the original link of where I saw the solution.

I hope this helps. Thanks!

0

精彩评论

暂无评论...
验证码 换一张
取 消