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:
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'
The keypress() method in jQuery triggers the keypress event whenever browser registers a keyboard input. So, Using keypress() method it can be detected if any key is pressed or not.
The keyup event is fired when a key is released. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup , but as 97 by keypress .
keyup(): Event fired when a key is released on the keyboard. keydown(): Event fired when a key is pressed on the keyboard. keypress:() Event fired when a key is pressed on the keyboard.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With