Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding jQuery click events to dynamically added content

Tags:

jquery

I have a table with multiple rows and columns populated by php and mySQL. For some of the td's I'm adding jQuery click-events in the document.ready function to let the user change the content.

But I also have an option for adding rows to the table and populating them manually. But since the rows I'm adding aren't there on the document ready, they won't get the click event handler appended, and so I'm not able to click them to get input boxes.

<table>
  <tr>
    <td class="clickable">Some info</td>
    <td class="clickable">Some more info</td>
    <td>Unchangable info</td>
  </tr>
  ... more similar rows ...
</table>

and then the jQuery

$("tr.clickable").click(function() {
   //add input fields
}

$("span#addNewRow").click(function() {
   $("table").append('<tr><td class="clickable"></td> ... </tr>')
}
like image 805
peirix Avatar asked May 12 '09 12:05

peirix


People also ask

How do you add an event to a dynamic button?

To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click .

How do you bind change event in jQuery for dynamically added HTML element?

If you try to bind the elements that are dynamically added to the DOM using the click() method of jQuery, this will not work, because it only binds the click event to elements that exist at the time of the “binding”. To bind the click event to all existing and future elements, use jQuery's on() method.

Does jQuery work on dynamic content?

You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content). The jQuery set receives the event then delegates it to elements matching the selector given as argument.

How can we call onclick function on dynamically created button in jQuery?

onclick = function () { alert("hi jaavscript"); };


2 Answers

You want to use live events, which were introduced in 1.3.

$("tr.clickable").live("click", function() {
   //add input fields
});

$("span#addNewRow").live("click", function() {
   $("table").append('<tr><td class="clickable"></td> ... </tr>')
});

UPDATE: Note that as of jQuery 1.7, live() is deprecated. Use on() instead. And in some cases, delegate() may be a better choice. See the comments below.

Example of how to use .on():

$("table").on("click", "tr.clickable", function() {
   //add input fields
});
like image 154
Plutor Avatar answered Oct 02 '22 14:10

Plutor


You can use .delegate() function which attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

like image 23
Tauseef Avatar answered Oct 02 '22 13:10

Tauseef