Jquery dynamic button : how to bind to exisitng click event by class
Posted
by
omer bach
on Stack Overflow
See other posts from Stack Overflow
or by omer bach
Published on 2012-12-11T10:57:24Z
Indexed on
2012/12/11
11:03 UTC
Read the original article
Hit count: 297
jQuery
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>
© Stack Overflow or respective owner