i use this code and it works
<HTML>
<HEAD>
<SCRIPT language=Javascript>
<!--
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<INPUT id="txtChar" onkeypress="return isNumberKey(event)"
type="text" name="txtChar">
</BODY>
</HTML>
but I do not have access to the html, and have only javascript
document.getElementById("txtChar").addEventListener("keypress", <<your code>>, false);
what should be in place <<your code>>
?
p.s. found another bug with this component:
when you copy-paste(ctrl-v or right click-paste) it does not work
can someone know how to resolve it
I know I'm a little late to the party.
The HTML5 example by jAndy is probably the best answer for browsers that support it. The JavaScript answer by Josaph was good as well in that it inspired my answer to solve the questioner's addendum and my problem.
The following throws away input that matches the regex (not a digit, replace with an empty string), and is invoked anytime there's input, even from a paste.
I'm not a JavaScript guy, I'm not sure if this is a good way to solve the problem, or if there are performance issues to consider. However, it works for me.
Try this code bro. i hope it will help you a lot i use jQUERY.
It's a mistake?
If you can't go with HTML5
<input type="number">
then I would regex the input value allowing only numbers. I modified a script I wrote to accomplish a similar task. It allows pasting and strips any non-integer character.Anyway, you can view the original script with tests here and a demo of the above code here.
event is unknown inside function. So mention the event object to function:
document.getElementById("myElement").addEventListener("keypress", function(event){ return isNumberKey(event); }, false);EDIT: The question changed a bit, so quoting the answer:
1. Change "myElement" to "txtChar"
2. include event object as parameter
In
<<your code>>
add the name of the function to handle it,isNumberKey
in this case; and also you need to addevt.preventDefault();
beforereturn false;
This function below only accepts codes corresponding to digits from 0 to 9 and ignores dots ("."), hyphens ("-") and minus signs ("−").
Configure the input field for HTML5 browsers:
Working example including styling from jAndy's answer: http://jsfiddle.net/pL9Zk/