Hunain Hafeez
Hunain Hafeez

Reputation: 187

Enter only digits in a textbox

I was using this function to enter only digits in to textbox and it worked.

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

but customer asked me to restrict - sign so user should not enter - sign. So I modified the code to this:

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode == 45)
        return false;

    return true;
}

and now it not works, it allows letters too, why?

Upvotes: 1

Views: 106

Answers (2)

Jai
Jai

Reputation: 74738

You need || in the group:

function isNumberKey(evt) {
  var charCode = (evt.which) ? evt.which : event.keyCode;
  var bool = (charCode > 31) && (charCode < 48 || charCode > 57 || String.fromCharCode(charCode) == "-");

  return !bool;

}
<input type="text" onkeypress='return isNumberKey(event)'>

Upvotes: 2

cl3m
cl3m

Reputation: 2801

You should use || instead of && in your test.
On my azerty keyboard, the - sign charcode is 54, not 45.

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57 || charCode == 45) )
        return false;

    return true;
}

See this fiddle

Edit

Looks like your charCode is correct. The 54 value comes from my azerty keyboard.
Nevertheless, you should use || instead of && in your check.

Upvotes: 1

Related Questions