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>
The standard answer here is event delegation. Hook
clickon the parent of all of these buttons, and ask jQuery to notify you only when the actual element clicked matches the selector, like this usingdelegate:…or like this in jQuery 1.7+ using the hyper-overloaded
on:Note the difference in the order of arguments. I prefer
delegatefor the explicitness of it.Live Example | Source
In either case, jQuery will hook
clickon#mainTable, but when the click occurs, only call your handler if an element matching.testBtnis 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.testBtnelement.Note that you can do the same for your
.addRowBtnif you like.