如何使用JavaScript通过ID获取数据并填充到HTML表格单元格中
存在的问题
你原来的代码存在以下几处错误,导致无法实现预期效果:
- 事件名不匹配:下拉框的
onchange属性写的是gettingList(),但实际定义的函数名是getList,选择商品后价格无法填充到对应输入框 - ID对应错误:计算总金额的逻辑里,要赋值的目标元素ID写的是
bill,但实际总金额输入框的ID是result,计算后的值无法正常显示 - 表格行插入位置错误:
insertRow(0)会把新行插入到表格最顶部,会出现在表头上方,应该用insertRow(-1)插入到表格最后一行 - 单元格赋值语法错误:给单元格赋值时多写了多余的小数点,且没有使用正确的内容属性,需要用
textContent填充单元格内容 - 商品名取值错误:
itemsList.value拿到的是商品的价格属性,需要获取选中option的文本内容才能得到商品名称
修复后的完整代码
<select id="itemsList" onchange="getList()"> <option>Please select the option</option> <option value="50">Soap</option> <option value="100">Sugar</option> <option value="290">Oil</option> </select> <br><br> <input type="number" id="price" disabled=""> <br><br> <input type="number" id="quantity" onChange="calculate()"> <br><br> <input type="number" id="result"> <button type="button" onclick="addDetails()">Add</button> <table id="myTable" border="1"> <tr> <th>Product Name</th> <th>Price</th> <th>Quantity</th> <th>Amount</th> </tr> </table> <br> <script> var getPrice = document.getElementById('itemsList'); function getList () { document.getElementById('price').value = getPrice.value; } function calculate () { var prc = document.getElementById('price').value; var qty = document.getElementById('quantity').value; var result = prc * qty; document.getElementById('result').value = result; } function addDetails () { var table = document.getElementById("myTable"); var row = table.insertRow(-1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); var cell4 = row.insertCell(3); var selectedItem = getPrice.options[getPrice.selectedIndex].text; cell1.textContent = selectedItem; cell2.textContent = document.getElementById('price').value; cell3.textContent = document.getElementById('quantity').value; cell4.textContent = document.getElementById('result').value; } </script>
内容的提问来源于stack exchange,提问作者Muhammad Ahmad
相关产品推荐
相关产品推荐

