Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch javascript event on fields created dynamically

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.

like image 679
Nathan H Avatar asked Aug 28 '26 11:08

Nathan H


1 Answers

YOu can use Jquery's live:

jQuery(".form_inputext1").live('keypress', function(event) {
      console.log(event.keyCode);
      if (event.keyCode == '13' || event.which == '13') {
         event.preventDefault();

         jQuery("#addMoreOptions").click();

         return false;
      }
});

Or you can add the keypress event when you create the element, which will give you much better performance:

$('.clicker').click(function() {
    $('<div class="clicker" />').text('new').appendTo($(this)).keypress(function(event) {
        alert(event.which);
    })
})

Example of that

like image 163
Joe Avatar answered Aug 30 '26 01:08

Joe