如何用jQuery实现表格多行下拉框选中值自动填充对应字段
问题原因
核心问题是HTML中重复使用了相同ID。ID在页面中必须唯一,jQuery通过$('#itemserialno')只会选中第一个匹配元素,所以只有第一行下拉框能触发填充逻辑。
解决方案
分两步修改代码:
1. 修改HTML:将重复ID替换为Class
在PHP循环生成表格行的代码里,把所有表单元素的id属性改成class(class允许重复),同时修正下拉框的name属性为数组形式(否则提交仅能获取最后一行值):
修改后的表格行代码片段:
<tr> <td><input style="font-size:15px" type="text" name="itemname[]" class="itemname" value="<?php echo htmlentities($result->requestitem_item);?>"></td> <td><input style="font-size:15px" type="text" name="itemcategory[]" class="itemcategory" value="<?php echo htmlentities($result->requestitem_category);?>"></td> <td><input style="font-size:15px" type="text" name="itembrand[]" class="itembrand" value=""></td> <td><input style="font-size:15px" type="text" name="itemquality[]" class="itemquality" value="<?php echo htmlentities($result->requestitem_no);?>"></td> <td><select name="itemserialno[]" class="itemserialno" required> <option>Select Name</option> <?php echo "<option value='$srlno' data-itmswybill='$itmwybl' data-itmsupply='$itmsplyno' data-itmbrnd='$itmbrnd' data-itmsra='$itmsra'>".$srlno."</option>";?> </select></td> <td><input style="font-size:15px" type="text" name="itemswybill[]" class="itemswybill" value=""></td> <td><input style="font-size:15px" type="text" name="itemsra[]" class="itemsra" value=""></td> <td><input style="font-size:15px" type="text" name="itemsupply[]" class="itemsupply" value=""></td> </tr>
2. 修改jQuery代码:事件委托+行内元素定位
改为针对当前下拉框所在的行查找对应输入框,同时用事件委托确保动态生成的行也能生效:
修改后的JS代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).on('change', '.itemserialno', function() { const selectedOption = $(this).find('option:selected'); const currentRow = $(this).closest('tr'); currentRow.find('.itemswybill').val(selectedOption.data('itmswybill')); currentRow.find('.itemsupply').val(selectedOption.data('itmsupply')); currentRow.find('.itembrand').val(selectedOption.data('itmbrnd')); currentRow.find('.itemsra').val(selectedOption.data('itmsra')); }); </script>
额外优化
原代码中表格和tbody的ID都是zctb,属于重复ID(不符合HTML规范),建议去掉tbody的ID:
<tbody>
内容的提问来源于stack exchange,提问作者ICTM
相关产品推荐
相关产品推荐

