首页 > 解决方案 > 尝试将文本框值添加为表格行

问题描述

我正在尝试读取 3 个文本框值:名字、姓氏和年龄,并在单击保存按钮后将它们添加为表格中的一行,但它不起作用。我的功能有什么问题?

function save()
{ 
var firstName= document.getElementById("txtFname").value;
var lastName=document.getElementById("txtLname").value;
var ageValue=parseInt(document.getElementById("age").value,10);

var table2=document.getElementById("dbtable");
var fNameValue= value.createTextNode(firstName);
var lNameValue= value.createTextNode(lastName);
var agetextnode=value.createTextNode(ageValue);

td1=document.createElement("td");
td2=document.createElement("td");
td3=document.createElement("td");

td1.appendChild(fNameValue);
td2.appendChild(lNameValue);
td3.appendChild(agetextnode);

tr1=document.createElement("tr");
tr1.appendChild(td1);
tr1.appendChild(td2);
tr1.appendChild(td3);

table2.appendChild(tr1);
}

标签: javascripttextbox

解决方案


如果您可以提供正在使用的完整 HTML/JavaScript 会有所帮助,这样我们就可以看到问题出在哪里。

我还建议扩展您的逻辑以使其更容易进行故障排除。你基本上有3个步骤:

  1. 获取输入的值
  2. 为新行生成标记
  3. 将行追加到表中

这是一个示例,这些示例如何符合您的要求。

function save () {
  const age = document.getElementById('age').value;
  const first = document.getElementById('firstName').value;
  const last = document.getElementById('lastName').value;
  const tbody = document.querySelector('#dtable tbody');
  tbody.appendChild(createRow(age, first, last));
}

function createRow(age, first, last) {
  const tr = document.createElement('tr');
  tr.appendChild(createTd(age));
  tr.appendChild(createTd(first));
  tr.appendChild(createTd(last));
  return tr;
}

function createTd(value) {
  const td = document.createElement('td');
  td.innerText = value;
  return td;
}
table {
  width: 100%;
}
<input type="number" id="age" placeholder="age" />
<input type="text" id="firstName" placeholder="First Name" />
<input type="text" id="lastName" placeholder="Last Name" />
<button onclick="save()">Save</button>

<table id="dtable">
  <thead>
    <tr>
      <th>Age</th>
      <th>First</th>
      <th>Last</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>


推荐阅读