1

我有以下代码,并且很好奇如何强制输入与自动完成的内容相匹配:

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

1 回答 1

0

回答这个问题是为了任何在 2013 年偶然发现这个问题的人的利益(是的,对!)

$("#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.
        }
    }
});

说明: map() 方法创建了一个 jQuery 对象,其中填充了从函数返回的任何内容(在本例中,是每个<li>元素的文本内容)。

get() 方法(当不传递参数时)将该 jQuery 对象转换为实际的数组。

这是我看到解决方案的原始链接。

我希望这有帮助。谢谢!

于 2013-06-20T13:19:42.963 回答