I am trying to add another row in a table(that contains form inputs) when the add button is clicked.
Here is my code:
$("#add_ingr").click(function(){
var row = '<tr>'
+'<td>'
+'<?php $data = array('name' => 'ingr_name[]', 'class' => 'ingr_name'); echo form_input($data); ?>'
+'</td>'
+'<td>'
+'<?php $data = array('name' => 'ingr_amount[]', 'class' => 'amt'); echo form_input($data); ?>'
+'</td>'
+'<td>'
+'<?php $data = array('name' => 'ingr_unit[]', 'class' => 'unit'); echo form_input($data); ?>'
+'<span class="remove">X</span>'+'</td>';
+'</tr>';
$("#ingr_table > tbody").append(row);
});
Whenever I would click the element with an ID of add_ingr, a new row would successfully be appended on the table but whenever I would click the x text which has the class of remove, this code never gets executed:
$("span.remove").click(function() {
alert('clicked');
$(this).parent().remove();
});
I don’t know what was wrong with it and I’ve been trying to find a solution for my problem but unfortunately, I can’t have things working.
Can somebody tell me what’s wrong with this? I would really appreciate your help. Thanks in advance.
The click handler is not being bound to the element. Either change your code to:
so that it
span.removeis always bound, or place the bind inside of your other click function:Also,
.parent()will select the<td>element, so I changed this to.closest('tr')which will select the closest table row.