0

I'm using the append method to add some input fields and a button to form, if the user needs to add more info. Each button has different different name and id, but same class.

The append process is working fine, but when I want to remove a specific field using the new button it does not work. The click action works for the first button, which is exists by default, but now for buttons added at run time.

   rc; //is the counter which increments by one, each time.
   jQuery('#mytable').append("<div id='rev-" + rc + "' class='reviewer'>" +
                             "<input type='text' name='reviewer_email[]' id='reviewer_email" + rc + "' value=''  />" +
   "<input type='button' name='rd" + rc + "' id='rd" + rc + "' class='rrd' value='Remove' /></div>");

   jQuery(".rrd").click(function(){
    alert("Test");
   });

I have searched for solution, first I was using the same id for all buttons but now I'm using same class for each button instead of id.

Can anyone give an idea, where I'm going wrong.

The above code is not the exact code, but idea, how I'm using it.

Thanks.

0

3 Answers 3

2

You can only use the .click() event handler for elements already added to the DOM.

For dynamically added elements you should use .on():

$(document).on("click", ".rrd", function(event){
    // do stuff
});

Or when using jQuery < 1.7 you should use .delegate():

$(document).delegate(".rrd", "click", function(event){
    // do stuff
});

Note that .live() is deprecated and also slower.

From the jQuery docs:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

Sign up to request clarification or add additional context in comments.

Comments

0

You binded the event on all the elements with class .rrd but this does not count for elements created dynamicly (after the page was loaded).

instead target the head element first then the actual element you want to delete.

Check this video, it is explained in details -> http://tutsplus.com/lesson/bind-live-delegate-huh/

1 Comment

@krike don't worry about it... I think "someone" just threw their rattle out of their pram :)
0

This isn't a direct solution to your issue but it may be a better solution for you in general. Have you considered using an existing plugin instead of having to develop everything yourself?

Have a look at SheepIt There may be others too but I've only used this one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.