对象HTMLInputElement出现而不是复选框

时间:2019-02-02 11:27:04

标签: javascript html

我试图在按下“添加项目”按钮后在“收集的”列中显示一个复选框,但是,出现了[object HTMLInputElement]。我已经尝试了appendChild,insertBefore和删除innerHTML,但是显然这使情况变得更糟。我曾尝试在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>

1 个答案:

答案 0 :(得分:0)

您需要使用appendChild而不覆盖单元格的innerHTML。您正在向DOM添加一个新元素。可以通过将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>