焦点丢失时自动完成检查

时间:2011-01-28 10:45:44

标签: jquery jquery-ui javascript jquery-autocomplete

如何确保输入字段中的值始终只有来自源的值?

例如,如果在源中我有

source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]

由数据库驱动,因为实际脚本是:

source: "get_json.aspx";

在输入字段中我输入“”,如何阻止这种情况发生?

当从输入字段中丢失焦点时,如何确保源中存在值?

1 个答案:

答案 0 :(得分:5)

你应该绑定到正确的事件。我认为你应该绑定到close event。然后检查value of input包含元素in array。否则,您应该使用val再次输入空。我在当地自己进行了测试,它可以解决问题。

$( "#tags" ).autocomplete({
    source: availableTags,
    close: function(event, ui) {
        var inputValue = $( "#tags" ).val();
        var idx = jQuery.inArray(inputValue, availableTags);
        if (idx == -1) {
            $( "#tags" ).val("");           
        }
    }
});

P.S:我做了一些测试,我认为你应该把它绑定到另一个事件上。因为当您选择导航栏时它不起作用。我认为你应该绑定到blur事件。

改进代码=>

$( "#tags" ).autocomplete({
    source: availableTags
});

$( "#tags").blur(function() {
    var inputValue = $( "#tags" ).val();
    var idx = jQuery.inArray(inputValue, availableTags);
    if (idx == -1) {
        $( "#tags" ).val("");           
    }
});

json to array =>

<强> json.txt:

[{"id":1,"value":"ActionScript"},{"id":2,"value":"AppleScript"},{"id":3,"value":"Asp"},{"id":4,"value":"BASIC"},{"id":5,"value":"C"},{"id":6,"value":"C++"},{"id":7,"value":"Clojure"},{"id":8,"value":"COBOL"},{"id":9,"value":"ColdFusion"},{"id":10,"value":"Erlang"},{"id":11,"value":"Fortran"},{"id":12,"value":"Groovy"},{"id":13,"value":"Haskell"},{"id":14,"value":"Java"},{"id":15,"value":"JavaScript"},{"id":16,"value":"Lisp"},{"id":17,"value":"Perl"},{"id":18,"value":"PHP"},{"id":19,"value":"Python"},{"id":20,"value":"Ruby"},{"id":21,"value":"Scala"},{"id":21,"value":"Scheme"}]

$(function() {
    var LIMIT = 10;
    $.getJSON("json.json", function(data) {
        var autocomplete = $( "#tags" ).autocomplete({
            source: function( request, response ) {
                var i=0;
                var result = [];
                $.each(data, function(index, value) {
                    // value.value.search(/request.term/i);
                    var idx = value.value.toLowerCase().indexOf( request.term.toLowerCase() );
                    if (idx >= 0) {
                        result.push(value.value);
                        i++;
                    }
                    if (i === LIMIT) {
                        return false;
                    }
                });
                response(result);
            }
        });

        $( "#tags").blur(function() {
            var inputValue = $( "#tags" ).val();
            var clear = true;
            $.each(data, function(index, value) { 
                if (value.value == inputValue) {
                    clear = false;
                    return false;
                }
            });
            if (clear) {
                $( "#tags" ).val("");
            }
        });
    });
});