Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input text field that only accepts numbers AND the dash character

Tags:

javascript

I'm using the commonly used Javascript function to allow only numbers to be inputted into a text field:

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

  return true;
}

I call this onkeypress and it prevents anything but numbers to display. I'm trying to alter it so it will allow me to also put dashes (-) into the text field. The dash keycode is 189 so I tried this:

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

  return true;
}

Thinking that the conditional statement would then accept the dash character but that didn't seem to work. Any ideas on why this would be? Thanks for your help!

like image 786
MillerMedia Avatar asked Dec 12 '22 10:12

MillerMedia


2 Answers

If you're using the keypress event you need to use the character code 45 for dash/hyphen.

If you're using the keydown/keyup events then you need to use 109 and 189 to cover the minus key in the numeric keypad and the one (usually) located above the P key.

if (charCode != 46 && charCode != 45 && charCode > 31
    && (charCode < 48 || charCode > 57))
     return false;

Demo: http://jsfiddle.net/J6B7U/

If you have doubts about which keycode is which a console.log(charCode); in your function will help you debug.

(Note also that trapping a key event is not enough to prevent invalid data being entered, because the user may change the field using the browser's edit menu or drag'n'drop.)

like image 65
nnnnnn Avatar answered Mar 09 '23 00:03

nnnnnn


try this

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

     return true;
  }

in html

<input type="text" onkeypress="return isNumberKey(event)">
like image 36
Yaşar Xavan Avatar answered Mar 09 '23 01:03

Yaşar Xavan