I'm kinda new to jQuery and just created the following: A table with a text field above it, the table shows matches in the database:
<script>
$('#searchRecept > #searchReceptAjax').keyup(function(){//Werkt dit?
var postRecept = $.post("../ajaxhandler.php?action=searchRecept", $('#searchRecept').serialize());
postRecept.done(function( data ) {
var response = $("<div>" + data + "</div>").find('tbody');
$('#recepten > tbody').replaceWith( response );
});
});
</script>
This works perfectly fine. Before that I created a link (one in every row of the tbody) to insert a new row after that row:
<script>
$('.addingredient').click(function(e){
$('<tr><td colspan="5">test</td></tr>').insertAfter($(this).closest('tr'));
});
</script>
The tbody looks like this:
<tbody>
<tr>
<td>Something...</td>
<td>Something else.</td>
<td>Probably some text here.</td>
<td>...</td>
<td>???</td>
<td><a href="#" class="addingredient">aap</a></td>
</tr>
</tbody>
I used the same php include in ajaxhandler.php (to create response) as on the initial page request - with other contents of course. However, after the tbody is changed by the first piece of javascript adding a row doesn't work anymore. Even if the tbody that comes from the response has the same data as in the initial request (when search string is empty).
Why doesn't this work? Any thoughts?
Kinds regards,
Niels
You can use event delegation to attach events for dynamically created elements:
$('body').on('click','.addingredient', function(e){
$('<tr><td colspan="5">test</td></tr>').insertAfter($(this).closest('tr'));
});