I'm trying to make it so I don't have a write a function for every input field I want to use this on. Rather sending the element id to the function and only having one function that I can recycle.
Works like this
<input name="field" id="field" type="text" onKeyPress="onlyNum()" />
<script type="text/javascript">
function onlyNum() {
var name = $("#field");
name.keypress(function (e) {
if (e.which > 0 && // check that key code exists
e.which != 8 && // allow backspace
!(e.which >= 48 && e.which <= 57) // allow 0-9
) {
e.preventDefault();
}
});
}
</script>
But it doesn't work like this, however this is what I'm going for:
<input name="field" id="field" type="text" onKeyPress="onlyNum('field')" />
<script type="text/javascript">
function onlyNum(theInput) {
var name = document.getElementById(theInput);
name.keypress(function (e) {
if (e.which > 0 && // check that key code exists
e.which != 8 && // allow backspace
!(e.which >= 48 && e.which <= 57) // allow 0-9
) {
e.preventDefault();
}
});
}
</script>
So does anyone know what's wrong with the second example? And how can I get that to work. Thanks
onKeyPress="onlyNum(this)"and thenthis.keypress(function(e) {...}). Are you using jQuery?