在jquery自动完成中将用户输入限制为可用列表

时间:2012-11-12 13:48:02

标签: jquery jquery-ui autocomplete

我正在使用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('');
        }
    }
});

2 个答案:

答案 0 :(得分:1)

我发现这个问题来检索下拉列表的选择! Get selected value in dropdown list using 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 
                    }
            }))
        }
    })
});

答案 1 :(得分: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 }
                }))
            }
        })
    }
});