Autocomplete check when focus is lost

How to ensure that the value in the input field always matters only from the source?

For example, if in the source I have

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

which is managed by the database since the actual script:

source: "get_json.aspx";

and in the input field type " cold ", how can I stop this?

How can I guarantee that this value exists in the source when focus is lost from the input field?

+3
source share
1 answer

. , . . , 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("");
            }
        });
    });
});
+4

Source: https://habr.com/ru/post/1788455/


All Articles