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
The problem with your second example is that you are trying to call
.keypresson a DOM element..keypressis a method of jQuery objects though.The whole approach is strange though. What are you trying to do is binding a new event handler to the element upon each key press. That is, after three keys have been pressed, you have assigned three event handlers to the same element which are all doing the same.
What you should be doing is assigning a class to each element that you want to bind the event handler to, select them with jQuery and bind the handler once.
For example:
Binding the handler:
If you cannot modify the HTML, then make use of the multiple selector and list the IDs:
That’s how jQuery works. You might want to read some of the tutorials to get a better idea of it.
Here is the less recommendable way to fix your code:
I already said that you are binding a handler to the
keypressevent inside thekeypressevent handler, which does not make sense. You already assigned the event handler via theonkeypressHTML attribute. You don’t need the ID of the element. All you have to do is pass theeventobject to your function.Example:
JavaScript:
The biggest difference with this approach is that
eventis a native event object, not a jQuery event object. That also means that callinge.preventDefault()will fail in IE8 and below since this method does not exist. Also you might have to usee.keyCodeinstead ofe.which. jQuery takes care of all these differences.