Link to home
Start Free TrialLog in
Avatar of Colin Brazier
Colin BrazierFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Regular expression with javascript, only numbers required

Hi experts,

Can someone tell me what the below javascript code is doing please?  I want to accept only numbers in my form fields, and it seems they accept 'x' (but no other non-numeric characters).  Ideally I'd like to accept negative numbers as well.

Here's the html:
<td align="left"><input style="text-align: center;" type="text" name="txtGames<?=$ctr?>" value="1" size="1" maxlength="1" onkeypress="return NumbersOnly(event)"/>

Open in new window


<script type="text/javascript">
function NumbersOnly(e)
{
var keynum;
var keychar;
var numcheck;

if(window.event) // IE
  {
  keynum = e.keyCode;
  }
else if(e.which) // Firefox/Opera
  {
  keynum = e.which;
  }
keychar = String.fromCharCode(keynum);

numcheck = /[^\d\b\0x7F]/;
return !numcheck.test(keychar);
}

</script>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Dan Craciun
Dan Craciun
Flag of Romania image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Colin Brazier

ASKER

HTH?  It certainly did!

Thanks Dan.
You're welcome.

Glad I could help!