I'm having trouble getting my event handler to fire. I'm calling JSON into the page as below. I then want to be able to click one of the buttons I have created which will execute the 'hello there' alert. It works with every other element on the page, but not the <button>
.
Can anyone help?
test.js
$(document).ready(function() {
$.getJSON('/api/v1/recipe/?format=json', function(data) {
$.each(data.objects, function(i, recipe) {
$('table#recipes').append('<tr><td>' + recipe.title + '</td><td>' + recipe.ingredients + '</td><td>' + recipe.method + '</td><td><button class="btn" type="button" id="rmv">remove</button></td></tr>');
});
});
$('rmv').on('click', function() {
alert('hello there!');
});
});
recipe.html
{% extends 'base.html' %}
{% block content %}
<div class="container-fluid">
<div class="row-fluid">
<div class="span6">
<form action='' method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="go baby!">
</form>
</div>
<div class="span6">
<table class="table table-striped table-bordered" id="recipes">
<tr>
<th>Title</th>
<th>Ingredients</th>
<th>Method</th>
<th>Remove</th>
</tr>
</table>
</div>
</div>
</div>
{% block recipes %}{% endblock recipes %}
{% endblock content %}
you have got the selector wrong it should be
$('#rmv')
and if you are appending the element dynamically you should use it like
$(document).on('click','#rmv',function(e) {
//handler code here
});
your loop in the ajax success call back will probably produce elements with duplicate ids, which is wrong, so as @Alnitak mentioned you can switch to class selector like after modifying the cde
$.getJSON('/api/v1/recipe/?format=json', function(data) {
$.each(data.objects, function(i, recipe) {
$('table#recipes').append('<tr><td>' + recipe.title + '</td><td>' + recipe.ingredients + '</td><td>' + recipe.method + '</td><td><button class="btn rmv" type="button" >remove</button></td></tr>');
});
});
and the selector will look like
$(document).on('click','.rmv',function(e) {
//handler code here
});
Try this. Move this code inside callback
$(document).ready(function() {
$.getJSON('/api/v1/recipe/?format=json', function(data) {
$.each(data.objects, function(i, recipe) {
$('table#recipes').append('<tr><td>' + recipe.title + '</td><td>' + recipe.ingredients + '</td><td>' + recipe.method + '</td><td><button class="btn" type="button" id="rmv">remove</button></td></tr>');
});
$('#rmv').on('click', function() {
alert('hello there!');
});
});
});
OR use jQuery.on
$(document).on("click", "#rmv",function() {
alert('hello there!');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With