PHP盘点系统动态表单如何通过JS点击商品列表逐行填充字段
解决方案
步骤1:修改表单结构,给表单行加统一标识
将PHP循环输出的表单行添加类名,方便JS定位:
<?php for ($i = 0; $i <= 50; $i++) { ?> <tr class="inventory-form-row"> <!-- 新增类名 --> <td> <INPUT TYPE="TEXT" NAME="item_code[<?php echo $i; ?>]" SIZE="6" VALUE=" <?php if (!empty($_POST["item_code"][($i)])) { echo $_POST["item_code"][($i)]; } ?>"></td> <td><?php if (!empty($_POST["item_code"][($i)])) { $result = FetchData($_POST["item_code"][($i)]); echo $result['category']; } ?> </td> <td> <?php if (!empty($_POST["item_code"][($i)])) { echo $result['item_name']; } ?></td> <td> <?php if (!empty($_POST["item_code"][($i)])) { echo $result['packing']; } ?></td> <td><INPUT TYPE="TEXT" NAME="quantity[<?php echo $i; ?>]" SIZE="5" VALUE=" <?php if (!empty($_POST["quantity"][($i)])) { echo $_POST["quantity"][($i)]; } else { echo ""; } ?>"></td> </tr> <?php } ?>
步骤2:替换原有JS函数
直接覆盖你原来的JS代码即可:
function fillForm(itemCode, itemName, packing) { // 获取所有表单行 const formRows = document.querySelectorAll('.inventory-form-row'); // 遍历查找第一个空行(item_code输入框无内容的行) for (let i = 0; i < formRows.length; i++) { const currentRow = formRows[i]; const codeInput = currentRow.querySelector('input[name^="item_code["]'); if (!codeInput.value.trim()) { // 填充商品编码 codeInput.value = itemCode; // 填充商品名称 currentRow.children[2].textContent = itemName; // 填充包装规格 currentRow.children[3].textContent = packing; // 光标自动定位到当前行数量输入框,直接录入即可 const quantityInput = currentRow.querySelector('input[name^="quantity["]'); quantityInput.focus(); // 填充完成直接退出循环,下次点击自动找下一个空行 break; } } }
步骤3:修改商品列表的输出代码
调整点击事件,传入商品三个字段参数,同时转义特殊字符避免JS语法错误:
<?php $dbh = dbh_get(); $sql = 'SELECT * FROM goods as goods(item_code, sort) order by human_sort(goods.item_code)'; $stmt = $dbh->prepare($sql); $stmt->execute(); while ($r = $stmt->fetch()) { // 转义特殊字符 $code = htmlspecialchars($r['item_code'], ENT_QUOTES); $name = htmlspecialchars($r['item_name'], ENT_QUOTES); $packing = htmlspecialchars($r['packing'], ENT_QUOTES); print ' <tr> <td class="buttonL" onclick="fillForm(\''.$code.'\',\''.$name.'\',\''.$packing.'\')">'.$r['item_code'].'</td> <td>'.$r['item_name'].'</td> <td>'.$r['packing'].'</td> </tr> '; } dbh_free($dbh); ?>
可选优化:添加商品快速搜索功能
针对5000条商品数据,在商品列表顶部添加搜索框,快速定位目标商品:
- 先加搜索框HTML:
<input type="text" id="goods-search" placeholder="搜索商品编码/名称" style="margin:10px 0;padding:5px;width:300px;">
- 新增对应JS逻辑:
document.getElementById('goods-search').addEventListener('input', function(e) { const keyword = e.target.value.trim().toLowerCase(); document.querySelectorAll('.buttonL').forEach(btn => { const row = btn.closest('tr'); const code = btn.textContent.toLowerCase(); const name = row.children[1].textContent.toLowerCase(); row.style.display = (code.includes(keyword) || name.includes(keyword)) ? '' : 'none'; }); });
内容的提问来源于stack exchange,提问作者Kilisi
相关产品推荐
相关产品推荐

