Javascript to accept only number for a form text field
Javascript07 Oct 2010
I've developed a cross browser compatability script to accept only numbers for a text field on the web page. This works based on the browser events. IE supports the Javascript events in a way which is completely different from the other browsers like Firefox, Google Chrome, etc.
window.event - construct can be used to tackle the events on Internet Explorer.
event - pass the event while invoking the function, which can be used to deal with the events on non IE browsers like Firefox and Chrome.
Include the above script on your page and invoke the function onlyNumbers function onkeypress event of the corresponding text field with a return statement.
Here is an example - try with the below text box
window.event - construct can be used to tackle the events on Internet Explorer.
event - pass the event while invoking the function, which can be used to deal with the events on non IE browsers like Firefox and Chrome.
<script type="text/javascript">
function onlyNumbers(evt)
{
var e = (window.event)?event:evt; // for cross browser compatibility
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)){
return false;
}
return true;
}
</script>
Include the above script on your page and invoke the function onlyNumbers function onkeypress event of the corresponding text field with a return statement.
<input type="text" name="p_request" maxlength="10" onKeyPress="return onlyNumbers(event)">
Here is an example - try with the below text box