-1

When the user presses a key, I want to remove characters that are not in the range 0-9, but this code isn't working: (jsfiddle)

$('input').on('keypress', function(event){
        var char = String.fromCharCode(event.which)
        var txt = $(this).val()
        if (!txt.match(/^[0-9]*$/)){
            var changeTo = txt.replace(char, '')
            $(this).val(changeTo).change();
        }
});

What am I doing wrong? Thanks

2
  • 1
    I think that using JQuery Validation (jqueryvalidation.org) plugin you can do it better... Commented May 18, 2014 at 11:11
  • 1
    keypress event is fired before value is change - that's why txt will not include the new value Commented May 18, 2014 at 11:13

1 Answer 1

1

Updated fiddle:

http://jsfiddle.net/JXYbC/3/

$('input').on('keypress', function(event){
    if (event.keyCode < 48 || event.keyCode > 57)
        return false;
});

But as Mikk3lRo pointed out, there are much better answers already on stackoverflow, because you should for example also allow the delete key, so the user can correct an input:

How to allow only numeric (0-9) in HTML inputbox using jQuery?

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.