使用用户输入追加表行

Append table row with user input

本文关键字:追加 输入 用户      更新时间:2023-09-26

我有一个数据表,如下所示-

<table class="table" id = "myTable>
    <tr>
      <td> <b> ID </b> </td>
      <td> <b> First Name </b> </td>
      <td> <b> Last Name </b> </td>
    </tr>

我有一个输入表单部分如下-

<form>
      <input type="text" id ="userID">
      <input type="text" id ="firstname">
      <input type="text" id ="lastname">
      <input type="submit">
</form>

有人能帮助我使用javascript将新行附加到包含从用户输入表单获得的数据的表中吗?

您不需要jQuery就可以做到这一点。只需使用javascript。你可以使用这样的功能:

HTML,带有点击提交按钮的功能。。

<table class="table" id = "myTable">
    <tr>
      <td> <b> ID </b> </td>
      <td> <b> First Name </b> </td>
      <td> <b> Last Name </b> </td>
    </tr>
</table>
<form action="">
    <input type="text" id ="userID" />
    <input type="text" id ="firstname" />
    <input type="text" id ="lastname" />
    <input type="submit" onclick="return fillTable();" />
</form>

JavaScript

function fillTable() {
  var table = document.getElementById("myTable");
  var row = table.insertRow(0);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);
  cell1.innerHTML = document.getElementById("userID").value;
  cell2.innerHTML = document.getElementById("firstname").value;
  cell3.innerHTML = document.getElementById("lastname").value;
  return false;
}

我为您构建了一个JSFiddle来说明该行为。