1

I have the following code. I want to validate just numeric only.

    $('.numericonly').keypress(function (e) {
     var regex = new RegExp("^[0-9]+$");
     var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
     if (regex.test(str)) {
        return true;
     }
     e.preventDefault();
     return false;
   });

When I use above code, backspace and tab doesn't work anymore. Can anyone help me to enable backspace and tab?

sawa
  • 165,429
  • 45
  • 277
  • 381
Nur Elah
  • 13
  • 4
  • 2
    What does this have to do with [tag:ruby-on-rails] or [tag:ruby]? This looks like pure [tag:javascript]. – Amadan Jan 14 '16 at 03:43

1 Answers1

0

I find the answer from my mentor, here they are :

$('.numericonly').keypress(function (e) {
    var regex = new RegExp("^[0-9]+$");
    var key = e.keyCode || e.which
    // Don't validate the input if below arrow, delete and backspace keys were pressed 
    if(key == 8 || key == 9) {
        return;
    }
    var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (regex.test(str)) {
        return true;
    }

    e.preventDefault();
    return false;
});

Above code work in Firefox and Chrome.

Nur Elah
  • 13
  • 4