Вопрос

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

Это было полезно?

Решение

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.

Другие советы

you can use this inside the event handler to refer the element to which the handler was registered to - in this case the input element.

The first parameter to the event handler is the event object, in the event object you can use event.target to target the actual element which triggered the event and event.currentTaget to refer the element in which the handler was registered.

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

Read more about this

Alternatively, when not using a selector as specific as a class (such as a $('#form').change) you can pass the event to the callback function like so:

    $('#SomeForm').change(function (event) {        
            if (event.target.id === "SomeElementId") {
            // do whatever you need. 
            }
     });
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top