0

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;
    }   

}

3
  • Why don't you use the maxlength attribute in the HTML? <input type='number' maxlength='4'/> Commented Dec 5, 2013 at 20:11
  • 2
    <input type='number' maxlength=4 /> Commented Dec 5, 2013 at 20:12
  • That doesn't work. HTML validate only the maxlength when you click at the submit button Commented Dec 6, 2013 at 7:55

2 Answers 2

2

You may try it with HTML like this:

<input type='number' maxlength='4'/>
Sign up to request clarification or add additional context in comments.

1 Comment

Mines well make it type=number
1

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);
            }
        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.