Reputation: 2395
I have a click event triggered by the class selector inside the jquery ready scope:
$(".testBtn").click(function()
{
alert("This Works");
});
This works fine for static buttons how ever this doesn't work for dynamic buttons which are added upon clicking the button with "addRowBtn" id. I'm guessing that it has something to do with that the button is created after the event is registered but still the new button has the 'testBtn' class so it makes sense it should work. Any idea what am i doing wrong and how to make the dynamic buttons registered to the class selector click event?
Here is the whole code, you can copy and paste into an html, click the 'add button' and try to click the added buttons. you'll see nothing happens.
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js'></script>
<script>
$(function()
{
$(".addRowBtn").click(function()
{
$("#mainTable tr:last").after("<tr><td><button class='testBtn'>NotWorking</button></td></tr>");
});
$(".testBtn").click(function()
{
alert("This Works");
});
});
</script>
</head>
<body>
<table id="mainTable">
<button class="addRowBtn">Add button</button>
<tr><th>Testing</th></tr>
<tr><td><button class='testBtn'>Working</button></td></tr>
</table>
</body>
</html>
Upvotes: 2
Views: 11596
Reputation: 1074495
The standard answer here is event delegation. Hook click
on the parent of all of these buttons, and ask jQuery to notify you only when the actual element clicked matches the selector, like this using delegate
:
$("#mainTable").delegate(".testBtn", "click", function(e) {
// ...
});
...or like this in jQuery 1.7+ using the hyper-overloaded on
:
$("#mainTable").on("click", ".testBtn", function(e) {
// ...
});
Note the difference in the order of arguments. I prefer delegate
for the explicitness of it.
In either case, jQuery will hook click
on #mainTable
, but when the click occurs, only call your handler if an element matching .testBtn
is in the lineage between the element that was clicked and the #mainTable
. It will call the handler as though it had been hooked to the .testBtn
element.
Note that you can do the same for your .addRowBtn
if you like.
Upvotes: 10
Reputation: 1190
use jquery's delegate function to apply the event handler to all instances now and in the future http://api.jquery.com/delegate/
Upvotes: 0