2

我正在使用 jquery ui(1.8.11) 自动完成插件。

它有一个简单的自定义行为来检查可用列表中是否存在该值。那是因为我想限制用户使用列表中可用的内容。如果输入不在列表中,它将删除框的内容。它工作正常。

但是下面的实现仍然允许用户编写任何不在选项中的内容。我宁愿不让他写一些不存在的东西。

那么有没有办法在没有选项时删除用户会写的字符?或者最好只让他在列表中有查找的字符序列。

到目前为止,这是我的代码

$("#autocomplete").autocomplete({
    autoFocus: true,
    delay: 200,
    source: function (request, response) {
        $.ajax({
            url: "/Country/Find", type: "GET", dataType: "json",
            data: { search: request.term, maxResults: 10 },
            success: function (data) {
                response($.map(data, function (item) {
                    return { label: item, value: item }
                }))
            }
        })
    },
    change: function (event, ui) {
        if (!ui.item) {
            $(this).val('');
        }
    }
});
4

2 回答 2

1

我发现这个问题是为了检索下拉列表的选择!使用 JavaScript 在下拉列表中获取选定值?但是要删除最后一个字符不知道...

$("#autocomplete").autocomplete({
autoFocus: true,
delay: 200,
source: function (request, response) {
    $.ajax({
        url: "/Country/Find", type: "GET", dataType: "json",
        data: { search: request.term, maxResults: 10 },
        success: function (data) {
            response($.map(data, function (item) {
                    var e = document.getElementById("ddlViewBy");
                    var strUser = e.options[e.selectedIndex].value;
                    if(strUser  != null)
                    {
                        return { label: item, value: item }
                    }
                    else
                    {
                        //remove last char 
                    }
            }))
        }
    })
});
于 2012-11-12T14:56:19.580 回答
1

我是这样做的:

$("#autocomplete").autocomplete({
    autoSelect: true,
    autoFocus: true,
    delay: 200,
    source: function (request, response) {
        $.ajax({
            url: "/Country/Find", type: "GET", dataType: "json",
            data: { search: request.term, maxResults: 10 },
            success: function (data) {
                //Check the length of the returned list if it's empty 
                if (data.length == 0) {
                    //Remove the last character from the input
                    $("#autocomplete").val(function (index, value) {
                        return value.substr(0, value.length - 1);
                    })
                    //Rerun search with the modified shortened input
                    $("#autocomplete").autocomplete("search");
                }
                response($.map(data, function (item) {
                    return { label: item, value: item }
                }))
            }
        })
    }
});
于 2012-11-12T15:51:04.823 回答