Am selecting an item from a select-option tag in a table to populate records from a database to fill another select-option tag, but unfortunately, it only works for the first table row. When I add another table row with jquery, it does not work in the new added table row.
The HTML table
<table class="table table-bordered table-hover">
<thead>
<tr>
<th width="2%"><input id="check_all" type="checkbox"/></th>
<th width="10%">Credit Type</th>
<th width="20%">Credit Account</th>
<th width="15%">Fund</th>
<th width="15%">Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="case" type="checkbox"/></td>
<td>
<select name="fund_id" class="form control" id="type_1">
<option></option>
<option value="23">Expense</option>
<option value="3">Fixed Asset</option>
<option value="8">Current Asset</option>
<option value="5">Current Liability</option>
<option value="4">Non-Current Liability</option>
</select>
</td>
<td>
<select id="credit_1" name="cr_ac" class="form-control" >
<option></option>
</select>
</td>
<td> <input type="text" name="fund[]" id="fund_1" ></td>
<td><input type="text" name="amount[]" id="amount_1"></td>
</tr>
</tbody>
</table>
The script that add new row to table
<script>
var i=$('table tr').length;
$(".addmore").on('click',function(){
html = '<tr>';
html += '<td><input class="case" type="checkbox"/></td>';
html += '<td><select name="fund_id" class="form-control" id="type_'+i+'"><option></option><option value="23">Expense</option><option value="3">Fixed Asset</option><option value="8">Current Asset</option><option value="5">Current Liability</option><option value="4">Non-Current Liability</option></select></td>';
html += '<td><select id="credit_'+i+'" name="cr_ac" class="form-control" ><option></option></select></td>';
html += '<td><input type="text" name="fund[]" id="fund_'+i+'"></td>';
html += '<td><input type="text" name="amount[]" id="amount_'+i+'"></td>';
html += '</tr>';
$('table').append(html);
i++;
});
</script>
The onchange function with ajax
<script>
for (var i = 1; i < 2; i++) {
(function(i) {
$(document).ready(function(){
$("#type_"+i).change(function(){
var id=$("#type_"+i).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "populate_debit_type.php",
data: dataString,
cache: false,
success: function(html){
$("#credit_"+i).html(html);
}
});
});
});
})(i);
}
</script>
The PHP script that fetch the db records
<?php
include "includes/kon/db_connect.php";
$id = $_POST['id'];
// query for options based on value
$sql = $link->query("SELECT * FROM accounts WHERE parent_id = '$id' OR ext_parent = '$id'");
while($row = mysqli_fetch_array($sql)) {
echo '<option value="'.$row['account_code'].'">'.$row['account_name'].'</option>';
}
?>
Thanks