I have an input field with class named “form_inputext1”.
I am doing some action when pressing ENTER, using this code:
jQuery(".form_inputext1").keypress(function(event) {
console.log(event.keyCode);
if (event.keyCode == '13' || event.which == '13') {
event.preventDefault();
jQuery("#addMoreOptions").click();
return false;
}
});
This part works fine. One of the things it does is it adds one more input field of class “form_inputext1” as a result of an ajax call.
The problem is this newly added field is not associated with the keypress event I wrote. I assume that’s because the jQuery code only attach the event to the existing fields, not to the fields added in the future.
How can I work around this? I want this function to apply to onkeypress even for inputs that are not in the DOM yet.
YOu can use Jquery’s live:
Or you can add the keypress event when you create the element, which will give you much better performance:
Example of that