Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Only Numeric values and Enter

Status
Not open for further replies.

aspvbnetnerd

Programmer
May 16, 2006
278
SE
The users should only be enabled to use numeric values

I found this and this works fine
Code:
function numbersonly() 
{
	if (event.keyCode < 48 || event.keyCode > 57) return false;

}

Then I wanted to add "carriage return"
I tried something like this

George
if (event.keyCode < 48 || event.keyCode > 57) || (event.keyCode = 13) return false;

Tried this to
if (event.keyCode < 48 || event.keyCode > 57) Or (event.keyCode = 13) return false;

To be honest I dont know anything about JavaScript
 
When is your function being called? I think you will need to check for the enter key pressed during an "onkeydown" event and not an "onkeyup" event. Also your if statement has some errors... try this:
Code:
if (event.keyCode < 48 || event.keyCode > 57 || event.keyCode = 13) return false;
 
It didn't work with your code.

Code:
<SCRIPT LANGUAGE="JavaScript">
function numbersonly() {
if (event.keyCode < 48 || event.keyCode > 57) return false;
}

</script>
<input type=text value="0" onkeypress="return numbersonly()">

George
 
This works:
Code:
function check(val) {
  if(val < 48 || val > 57 || val == 13) {
   return false;
  } else {
   return true;
  }
}
....
<input type="text" ..... onkeydown="check(event.keyCode);">

The problem with this is that this code will not allow you to delete anything in the text box, or allow you to tab to a next field.

 
13 is in the range of <48, so adding the last condition is obviously making not much sense!

Do this?
[tt]
<SCRIPT LANGUAGE="JavaScript">
function numbersonly(evt) {
var nkeycode=(window.event)?window.event.keyCode:evt.which;
if (nkeycode < 48 || nkeycode > 57) {
return false;
} else {
return true;
}
}
</script>
<input type=text value="0" onkeypress="return numbersonly(event)">
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top