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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Number type to the input

Status
Not open for further replies.

ibike

Programmer
Apr 7, 2003
27
IT
Hello,
Can somebody tell me if into my 'input' I'd like to accept only just the number type, how can I handling this with use the 'style' from the stylesheet elements?
 
post this in the javascipt section, it cannot be done with CSS.

Known is handfull, Unknown is worldfull
 
Try this:

<html>
<head>
<script language=&quot;JavaScript&quot;>

function OnlyDigits(TheInput)
{
var msg=TheInput.value;
var chr;
for ( i=0; i < msg.length; i++ )
{
chr=msg.substring(i, i+1);
if ( chr < &quot;0&quot; || chr > &quot;9&quot; )
{
msg=msg.substring(0, i);
TheInput.value=msg;
}
}
}

</script>
<title>MyTitle</title>
</head>

<body>
<form name=&quot;MyFormform1&quot; method=&quot;post&quot; action=&quot;Mypage.html&quot;>
<input name=&quot;DigitsOnly&quot; type=&quot;text&quot; value=&quot;&quot;
size=&quot;30&quot; onKeyUp=&quot;OnlyDigits(this)&quot;><br>
<input type=&quot;Submit&quot; value=&quot;SendMe&quot;>
<input type=&quot;Reset&quot; value=&quot;ResetMe&quot;>
</form>
</body>
</html>

Hope this helps,
Erik

<-- My sport: Boomerang throwing !!
!! Many Happy Returns !! -->
 
This solution will prevent anything but digits as the user types:

function numOnly(event, field)
{
var eventKey, keychar;

if (window.event)
{
eventKey = window.event.keyCode;
}
else if (event)
{
eventKey = event.which;
}
else
{
return true;
}

//turn the event code into a real character
keychar = String.fromCharCode(eventKey);

//if it's a number we'll work with it, otherwise we won't
if ((&quot;0123456789&quot;).indexOf(keychar) > -1)
{
return true;
}
//no number entered, don't accept it
//you can also insert an alert if you
//want users to know they can enter only digits
//As is, if the user types a non-digit, nothing
//happens at all
else
{
return false;
}

}

The call looks like this:
<input type=&quot;text&quot; name=&quot;txtBox&quot; onkeypress=&quot; return numOnly(event, this)&quot;>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top