I have a button that when clicked inserts a form input field and a button (to delete) into the form using JQuery .after(). This works fine.
The button that is inserted has a function .click that should run when it is clicked – it is not working.
<script type="text/javascript">
$("#addAQuestion").click(function(){
var begin = "<tr>";
var question = "<td><input type='text' name='question'/>";
var deleteButton = "<input type='button' class='deleteQuestion' name='delete' value='Del' /></td>";
var end = "</tr>";
$("#questions").after(begin + question + deleteButton + end);
});
$(".deleteQuestion").click(function(){
alert('test');
//$(this).parent().empty();
});
</script>
How come the alert is not being triggered when a user clicks on the .deleteQuestion button?
Thanks!
Order of execution. The code that adds the nodes to the DOM is asynchronous – it happens on click. So, essentially, you’re attaching click events to
.deleteQuestionnodes before those elements are in the DOM.There are two ways to fix this.
1) Fix the order of execution so that the click events will be properly attached
2) Or, you can use jQuery’s live() function to handle this for you via event delegation