Search code examples
jqueryelementtyping

How to determine which element fired on .keyup jquery method call?


For example:

  $('.input-xlarge').keyup(function(element) {
              element.parent().parent().removeClass("error success");
          });

Scenario:

I have many input fields under class .input-xlarge, they are colored green or red depending on success state after form is submitted. (non-ajax form)

Now I want it to be more user friendly - as field state is returned back from the server my field keeps glowing red until next submit with valid input is initiated.

What is required:

Therefore after user submitted form, received some fields - some in valid, some in invalid state I want field to be neutral decoration whenever user starts typing inside.

What does not work:

From the code I provided I expect:

  1. to trigger event for any input field with class .input-xlarge whenever user starts typing.
  2. Indicate which input field exactly requires changing of css decoration(removing css classes) to neutral white.

Unfortunately I can't seem to extract the actual input element which triggered .keyup event. Is it possible to do this?

As you can see I know the exact navigation towards the css element afterwards but the root object ends up with an error:

Uncaught TypeError: Object #<Object> has no method 'parent' 

enter image description here


Solution

  • Inside a function, you can use this to get the element who triggered the function. Use this:

    $('.input-xlarge').keyup(function() {
        $(this).parent().parent().removeClass("error success");
    });
    

    The first parameter in the function is the event. An other way would be to use currentTarget on the event object (which is the same as this):

    $('.input-xlarge').keyup(function(e) {
        $(e.currentTarget).parent().parent().removeClass("error success");
    });
    

    Also, don't be affraid to use console.log(). Using it in the case would have show you that element was an event.