3

I have following code snippet:

    var reg = /^[0-9]$/;

    $('input[type="text"]').keypress(function(){
       console.log(reg.test(parseInt($(this).val())));
    });

When I press any key (digit or other) it always return false. But I can't find out the problem.Please give me some solutions.

1
  • 1
    Because at the time the handler is executed, the value of the field is not updated yet. It is an empty string (if there is no default value). You can easily test this with: console.log($(this).val()); Commented Apr 24, 2011 at 8:18

3 Answers 3

3

See How to allow only numeric (0-9) in HTML inputbox using jQuery? for a proper solution.

In case you want to do something own, have a look at those plugins anyway. It's very important to not break common things like backspace (or ctrl+c/v/x) as users usually expect those keys to work.

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

Comments

1

The regex you've created tests for exactly 1 occurance of any digit. It also asserts that it's the begining of the string followed by a single digit, then the end of string.

The keypress event is triggered before actual content is put into the textbox. This should only work for the second key press, because that's when the textbox content .val() yields exactly 1 digit.

If you follow the link posted by @ThiefMaster you'll find the answer to your question. You'll also note that it's using the charCode and keyCode properties of the event object to do validation not the contents of the textbox.

Comments

0
 $("#txtBoxID").keypress(function (event) {
            var reg = /[\d\.]/g;
            if (!reg.test((event.key))) {
                return false;
            }                      
        });

I have done like above, I have used keypress and its event and one regular function which will allow user to enter only DIGITS in text box/ input box.

You can check event.key , which give value of key has bee

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.