Search code examples
javascriptjquerykeycode

Capture keycode on input's with same class


I have a page with many text input's. All input's share the same class for many reasons.

Now I am trying to capture a the ESC button when an input is focused and alert if the input has value or not.

Now this logically works only for the first field. After the first field, since all input's share the same class, when I press ESC button it gives you the value of the very first input.

So how can I say that I'm talking for the second, fifth or whatever input I am pressing ESC on.

Here is an example: http://jsfiddle.net/Y5e9W/

The first input works fine, the second input thought; when you press ESC it gives you the values of the first.


Solution

  • You should be able to bind the keyup event to the elements with your class, rather than the document. Then this will refer to the element with focus:

    $(".gp").keyup(function(e) {
        if(e.which === 27) {
            if(this.value.length > 0) {
                //Has a value!
            }
            else {
                //Empty!
            }
        }
    });
    

    Here's an updated fiddle. Note that I've used the which property of the event object, which jQuery exposes to deal with browser differences between keyCode and charCode.

    Update based on comments

    If you do need to handle this at the document level, you can use the has method to narrow down your selection of .gp elements to the one which has focus:

    if (gj.has(":focus").val() != 0) { //...
    

    Here's another fiddle.