I have a table row where I added the ability to add/remove using .clone and .remove
I also have an ajax call to my controller in code igniter to grab the data and populate the other inputs based on data.
It currently works one the first one, I am able to select an option from the dropdown and it fills the values of the neighboring inputs. My problem is when I click add and it successfully clones the row, when I change that dropdown its like the .change and .ajax events no longer work.
Here is my jQuery which is here I think I am having the problem:
$('.invoice_line_item').each(function(){
$(this).change(function(){
var table = $(this).closest('.tr_clone');
var select_value = $(this).val();
//alert(item_id + ' ' + select_value);
console.log(item_id + select_value);
$.ajax({
url: '<?php echo site_url("Invoice_item/get_item"); ?>',
type: 'POST',
dataType: "JSON",
data: ({'id' : select_value}),
success: function (data, status)
{
//alert('Success ' + data);
console.log(data);
$(table).find('.description').val(data['work_description']);
$(table).find('.amount').val(data['amount']);
$(table).find('.quantity').val(data['quantity']);
$(table).find('.price').val(data['amount']);
},
error: function (data, xhr, desc, err)
{
alert('An Error Occurred: ' + xhr + ' ' + desc + ' ' + err);
console.log(data);
}
});
});
});
Here is the HTML:
<tbody>
<tr class="tr_clone" id="inv_line_1">
<td>
<select id="line_item_1" name="invoice_line_item" class="invoice_line_item">
<option></option>
<?php
foreach($prefix_line_items as $line_item)
{
?>
<option value="<?php echo $line_item['id']; ?>"><?php echo $line_item['item']; ?></option>
<?php
}
?>
</select>
</td>
<td><input type="text" id="description_1" name="description" class="description" value="" /></td>
<td><input type="currency" id="amount_1" name="amount" class="amount" value="" /></td>
<td><input type="number" id="quantity_1" name="quantity" class="quantity" value="" /></td>
<td><input type="currency" id="price_1" name="price" class="price" value="" readonly/></td>
<td><a href="#" onclick="return false;" class="add-line-item"><i class="fa fa-plus"></i></a> <a href="#" onclick="return false;" class="remove-line-item"><i class="fa fa-minus"></i></a></td>
</tr>
</tbody>
No errors in console, works the first time for the first row but when I click the Add button and it duplicates the row, I change the (cloned) select element and its like the jQuery no longer fires so it isnt grabbing the data via ajax or printing to the console.
While cloning the element, by default, it does not copy the event handlers to new elements. For that you have to pass true to tell clone method to do so. Good practice is to clone the element and then copy only required events manually to the new element.
Check below example given on jquery's website,
/ Original element with attached data
var $elem = $( "#elem" ).data( "arr": [ 1 ] ),
$clone = $elem.clone( true )
Hope it helps..
</div>