-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

Jodes
  • 14,118
  • 26
  • 97
  • 156

1 Answers1

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?

Community
  • 1
  • 1
Stephan Wagner
  • 990
  • 1
  • 8
  • 17