0

I am using the following jquery function to only allow numeric input. It works fine, but client now wants to limit input to 8 numeric values. Is there away, using the code below to also restrict the number of characters?

$(document).ready(function () {
    $('input.numberinput').bind('keypress', function (e) {
        return !(e.which != 8 && e.which != 0 &&
                (e.which < 48 || e.which > 57) && e.which != 46);
    });
});​

Thank you in advance.

2
  • Just add a && (this.value.length >= 8); in your current return statement and it should work fine. Commented May 9, 2013 at 13:49
  • 1
    Could you not just put a maxlength attribute on the <input> tag? Commented May 9, 2013 at 13:58

3 Answers 3

4

Try this

$(document).ready(function () {
$('input.numberinput').bind('keypress', function (e) {
   if(this.value.length>= 8) 
          {
            alert('Maximum limit is 8'); return false;
          }
    return !(e.which != 8 && e.which != 0 &&
            (e.which < 48 || e.which > 57) && e.which != 46);
});

});​

Sign up to request clarification or add additional context in comments.

Comments

0

You can "maxlength" to restrict user

Comments

-1

Just check this.value.length, for example:

if(this.value.length >= 8) {
   alert('maximum of 8 characters.');
}

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.