问题描述:

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;

}

}

网友答案:

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);
            }
        });
相关阅读:
Top