JQuery input restriction text box

Therefore, I need to have an input field in which people are allowed to enter either the words “Yes” or “No”. No other entry is allowed. Does anyone know a plugin or any other easy way with jQuery? I found a plugin called constraint ( http://plugins.jquery.com/project/constrain ) that can prevent the user from entering certain characters, but this is not enough, because For example, the plugin can prevent the user from entering numbers in the alphabetical field. Dropdown windows or other components are not an option.

Thank you for your help.

+3
source share
2 answers

Why not something like this ( link to jsFiddle )? This will allow you to enter only those characters that are contained in an array of valid values? I suspect there is a better way to check for values ​​or partial values ​​in an array instead of loops. But it will be triggered by pressing the user key, and not when the control loses focus ... so that the UX could be better.

Hope this helps!

HTML

Enter text: <input type="text" id="data" />

JavaScript code

var allowedValues = ['yes','no'];
$(document).ready(function() {
    $("#data").keyup(function(e) {
        var typedValue = $(this).val(),
            valLength = typedValue.length;
        for(i=0;i<allowedValues.length;i++) {
            if(typedValue.toLowerCase()===allowedValues[i].substr(0,valLength)) {
                return;
            }
        }
        $("#data").empty().val(typedValue.substr(0, valLength-1));
    });
});
+1
source

Based on the explanation in the comment, try the following:

Try: http://jsfiddle.net/fsPgJ/2/

EDIT: Added an event keypressto deal with the user holding the key.

$('input').blur(function() {
    var val = this.value.toLowerCase();
    if(val != "yes" && val != "no") {
        this.value = '';
        alert( "'Yes' or 'No' is required. \n Please try again.");
    }
})
    .keypress(function() {
        var val = this.value.toLowerCase();
        if(val != "yes" && val != "no")
            this.value = '';
    })
    .keyup(function() {
        var val = this.value.toLowerCase();
        if("yes".indexOf(val) != 0 &&
           "no".indexOf(val) != 0) {
               this.value = this.value.substr(0,this.value.length - 1);
           }
    });

Original:

, <select> :radio - , jQuery .blur().

: http://jsfiddle.net/fsPgJ/

$('input').blur(function() {
    var val = this.value.toLowerCase();
    if(val != "yes" && val != "no") {
        this.value = '';
        alert( "'Yes' or 'No' is required. \n Please try again.");
    }
});

, ( ) "" "". alert(), , . , .

0

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


All Articles