Question

I have a numbered input field, in that field only the character 0-9 and decimal points(,) are legid. That piece of code is done. But now I want to give the inputfield a maximum length of 4.

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode;

    if (charCode == 44){
        return true;
    } else if (charCode > 31 && charCode < 48 || charCode > 57){
        return false;
    } else{
        return true;
    }   

}

No correct solution

OTHER TIPS

You may try it with HTML like this:

<input type='number' maxlength='4'/>

simple

<input type='number' maxlength='4'/>

or if you want to allow some combination keys

$(function() {

            $ ('#input-field').keydown ( function (e) {
                //list of functional/control keys that you want to allow always
                var keys = [8, 9, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 144, 145];

                if( $.inArray(e.keyCode, keys) == -1) {
                    if (checkMaxLength (this.innerHTML, 4)) {
                        e.preventDefault();
                        e.stopPropagation();
                    }
                }
            });

            function checkMaxLength (text, max) {
                return (text.length >= max);
            }
        });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top