Nathan H
Nathan H

Reputation: 49421

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.

Upvotes: 3

Views: 218

Answers (4)

aziz punjani
aziz punjani

Reputation: 25776

Use .live():

$('.form_inputext1').live('keypress', function ( event ) {

});

Upvotes: 0

Joe
Joe

Reputation: 82624

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

Upvotes: 3

CodeThug
CodeThug

Reputation: 3202

If you use the jQuery live method to bind an event to a class, it will apply even to elements that are added to the DOM after you call the live method.

Documentation: http://api.jquery.com/live/

From the documentation:


To bind a click handler to the target element using this method:

$('.clickme').live('click', function() {
  // Live handler called.
});

And then later add a new element:

$('body').append('Another target');

Then clicks on the new element will also trigger the handler.

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 92943

Use .live() or .delegate() instead.

http://api.jquery.com/live/

http://api.jquery.com/delegate/

Upvotes: 0

Related Questions