javascript input allowing only numbers

javascript

Solution

If you're cool in using `HTML5` and only target modern browsers, the new attributes `required` and `pattern` are here for you. Example:

<input id="txtChar" type="number" required pattern="\d+"/>

and you can address the state via CSS like

#txtChar:required:valid {
    border: 1px solid green;
}

#txtChar:required:invalid {
    border: 1px solid red;
}

If used within a `<form>` tag, a user won't be able to submit in invalid state.

I just read that you don't have access to the markup, so apologizes. I'll just leave it as informational answer.

Problem

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

Original source