0

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

2
  • Try changing to onKeyPress="onlyNum(this)" and then this.keypress(function(e) {...}). Are you using jQuery? Commented Aug 11, 2012 at 9:07
  • If you are using jQuery, then the code above is grossly inefficient and somewhat unnecessary. Commented Aug 11, 2012 at 9:08

1 Answer 1

2

The problem with your second example is that you are trying to call .keypress on a DOM element. .keypress is 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:

<input name="field" id="field" type="text" class="someClass"/>

Binding the handler:

// will bind the event handler to each 'input' field with class 'someClass'
$('input.someClass').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();
    }
});

If you cannot modify the HTML, then make use of the multiple selector and list the IDs:

// adds the event handler to the elements with the IDs 'field', 'someID' and
// 'someOtherID'
$('#field, #someID, #someOtherID').keypress(function() {
    //...
});

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 keypress event inside the keypress event handler, which does not make sense. You already assigned the event handler via the onkeypress HTML attribute. You don't need the ID of the element. All you have to do is pass the event object to your function.

Example:

<input name="field" id="field" type="text" onKeyPress="onlyNum(event)" />

JavaScript:

function onlyNum(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();
    }
}

The biggest difference with this approach is that event is a native event object, not a jQuery event object. That also means that calling e.preventDefault() will fail in IE8 and below since this method does not exist. Also you might have to use e.keyCode instead of e.which. jQuery takes care of all these differences.

Sign up to request clarification or add additional context in comments.

3 Comments

Sorry I'm figuring this out as I go. Looks clean and efficent but don't I still need to write a new handler for every input?
No. $('input.someClass') is supposed to select every element you want to bind the handler to. jQuery takes care of binding the function you pass to .keypress to each of the selected elements. That's how it works and that's what makes it so comfortable to use.
I added this just to give a complete picture. If you use jQuery anyway, you should use it to bind the event hander, don't mix markup (HTML) with logic (event handling).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.