我正在從表中的選擇選項標籤中選擇一個項目,以填充數據庫中的記錄以填充另一個選擇選項標籤,但不幸的是,它僅適用於第一個表格行。當我用jQuery添加另一個錶行時,它在新添加的表格行中不起作用。onchange僅適用於表中的第一行
的HTML表格
<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>
增加新行到表中的腳本
<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>
使用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>
的功能電平變化3210
PHP腳本因爲你註冊的change
事件之前動態創建&注入新行時獲取數據庫記錄
<?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>';
}
?>
感謝
我是否必須再次使用(for循環)?你能幫我拿出ajax嗎?謝謝 – ASM
請onchange現在完美工作,但問題是在Ajax的成功功能。它只填充第一行 – ASM
您應該使用'nearest()'和'find()'。我更新了答案。 – Shyju