Search code examples
javascriptjqueryvalidationkeypress

If it is Possible to allow only certain text in input box in JQuery keypress event


If it Possible to allow specific string in input box in keyPress event in same order.Important thing is i need to allow only in the same order.

Example:If I need to allow "NILL" user must enter in the same order.If user enter "NL" then we need to restrict them.If it possible.

I've tried the following:

$("input").keypress(function(e) {
    var chr = chr = e.key;
    if ("NILL".indexOf(chr) < 0 && e.which != 13)
        return false;
        console.log('allowed');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="foo" />


Solution

  • You can transform the string into an array of chars then check each index if it matches the key entered

    $(document).ready(function(){
    
    var restriction = "NILL";
    restriction = restriction.split(''); // transform to array of char
    $("input").keypress(function(e) {
        var chr = e.key.toUpperCase();
        if(restriction[$(this).val().length] != chr){
        return false;
        }
    });
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" name="foo" />