Jquery dynamic button : how to bind to exisitng click event by class
- by omer bach
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>