简体   繁体   English

对象HTMLInputElement出现而不是复选框

[英]object HTMLInputElement appears instead of checkbox

I'm trying to have a checkbox appear in the Collected column after pressing the Add Item button however, [object HTMLInputElement] appears instead. 我试图在按下“添加项目”按钮后在“收集的”列中显示一个复选框,但是,出现了[object HTMLInputElement]。 I've tried appendChild, insertBefore and removing innerHTML but obviously that's made things worse. 我已经尝试了appendChild,insertBefore和删除innerHTML,但是显然这使情况变得更糟。 I've tried searching on Google and Stackoverflow for similar questions for relevant answers but no one's had a similar situation to me. 我曾尝试在Google和Stackoverflow上搜索类似问题以获取相关答案,但没有人遇到类似的情况。

 function addItem() { var a = String(document.getElementById("it").value); var b = parseFloat(document.getElementById("iq").value); if (a.length === 0 || isNaN(b)) { window.alert("Required field empty, please enter values in both boxes."); } else { var table = document.getElementById("list"); var row = table.insertRow(-1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); var cb = document.createElement("INPUT"); cb.setAttribute("type", "checkbox"); cell1.innerHTML = a; cell2.innerHTML = b; cell3.innerHTML = cb; } } 
 <table id="list" align="center"> <tr> <td colspan="3"> <input id="it" name="item" type="text" placeholder="Item" /> <input id="iq" name="quantity" type="text" placeholder="No." /> <br /> <input value="Add Item" type="submit" onclick="addItem()" /> <hr /> </td> </tr> <tr> <td><span>Item</span></td> <td><span>Quantity</span></td> <td><span>Collected</span></td> </tr> </table> 

You need to use appendChild and not overwrite the innerHTML of the cell. 您需要使用appendChild而不覆盖单元格的innerHTML。 You are adding a new element to the DOM. 您正在向DOM添加一个新元素。 This can be done by writing the HTML into the cell, but you have created the element so just append it.. 这可以通过将HTML写入单元格来完成,但是您已经创建了元素,因此只需附加它即可。

 function addItem() { var a = String(document.getElementById("it").value); var b = parseFloat(document.getElementById("iq").value); if (a.length === 0 || isNaN(b)) { window.alert("Required field empty, please enter values in both boxes."); } else { var table = document.getElementById("list"); var row = table.insertRow(-1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); var cb = document.createElement("INPUT"); cb.setAttribute("type", "checkbox"); cell1.innerHTML = a; cell2.innerHTML = b; cell3.appendChild(cb); } } 
 <table id="list" align="center"> <tr> <td colspan="3"> <input id="it" name="item" type="text" placeholder="Item" /> <input id="iq" name="quantity" type="text" placeholder="No." /> <br /> <input value="Add Item" type="submit" onclick="addItem()" /> <hr /> </td> </tr> <tr> <td><span>Item</span></td> <td><span>Quantity</span></td> <td><span>Collected</span></td> </tr> </table> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM