新增表格行时如何为行内下拉框填充数据库中的数据
修正方案
1. 修正HTML代码错误
首先移除多余的闭合标签,将重复的id属性改为class(同一页面不能存在重复id,否则JS选择会失效),移除行内onchange事件,改为后续用事件委托绑定:
<tbody> <tr> <td><input type="checkbox" name="record"></td> <td> <select class="catid" name="catid[]"> <option value="">Select Category</option> <?php $getcatid = "SELECT catid,catname FROM category"; $result = mysqli_query($conn,$getcatid); while($row = mysqli_fetch_array($result)){ ?> <option value="<?php echo $row['catid']; ?>"><?php echo $row['catname']; ?></option> <?php }?> </select> </td> <td> <select class="itemid" name="itemid[]"> <option value=''>Select Item</option> </select> </td> <td> <select class="msr" name="msr[]"> <option value=''>Measurement</option> </select> </td> <td><div class="price"><input type="text" name="price[]"></div></td> <td><input type="text" name="qty[]"></td> <td><input type="text" name="total[]"></td> </tr> </tbody>
2. 重写JS逻辑
利用首行已加载的分类下拉作为模板,新增行时直接复用选项,同时用事件委托处理所有行的下拉联动逻辑,保证新增的行也能正常触发数据加载:
$(document).ready(function(){ // 提前存好分类下拉的选项模板 const catOptionTpl = $('select.catid').first().html(); // 新增行逻辑 $("#add-row").click(function(){ const markup = ` <tr> <td><input type='checkbox' name='record'></td> <td><select class="catid" name="catid[]">${catOptionTpl}</select></td> <td><select class="itemid" name="itemid[]"><option value=''>Select Item</option></select></td> <td><select class="msr" name="msr[]"><option value=''>Measurement</option></select></td> <td><div class="price"><input type="text" name="price[]"></div></td> <td><input type="text" name="qty[]"></td> <td><input type="text" name="total[]"></td> </tr> `; $("table tbody").append(markup); }); // 删除行逻辑 $("#delete-row").click(function(){ $("table tbody").find('input[name="record"]').each(function(){ if($(this).is(":checked")){ $(this).parents("tr").remove(); } }); }); // 分类下拉联动加载项目(事件委托适配新增行) $(document).on('change', 'select.catid', function() { const currentTr = $(this).closest('tr'); const catid = $(this).val(); const itemSelect = currentTr.find('select.itemid'); // 这里写你原来加载项目的AJAX逻辑,请求后端返回对应分类的项目列表,塞入itemSelect即可 // 示例逻辑: // $.post('get_items.php', {catid: catid}, function(res) { // itemSelect.html(res); // }) }); // 计量单位下拉联动加载价格(事件委托适配新增行) $(document).on('change', 'select.msr', function() { const currentTr = $(this).closest('tr'); const itemid = currentTr.find('select.itemid').val(); const msr = $(this).val(); const priceInput = currentTr.find('.price input'); // 调用你原来的showPrice逻辑,把返回的价格赋值给priceInput即可 }); });
你原来首行加载下拉的逻辑可以直接复用,只需要把选择器改成按当前行查找元素,不要用id选择,就可以适配所有新增的行。
内容的提问来源于stack exchange,提问作者kajol
相关产品推荐
相关产品推荐

