如何使用Javascript表单元素填充html表?

问题描述 投票:0回答:1

基本上我想显示10行表格,并在提交表格时用人名更新。所以基本上我需要将表单输入写入表格单元格。当超过10人填写表格时,我希望表格只显示10,所以它会碰到其中一个早期的表格。到目前为止这是我正在尝试但我真的不知道如何继续。

<html>
<h2>Change Our Lights:</h2>
<form name="leds" id="ledSend" method="get" target="_blank" action="https://agent.electricimp.com/Fk43xPMkSrWF">
Lamp Control: <input type="radio" name="led" value="0" checked>Off
              <input type="radio" name="led" value="1">On<br>
How long should the Lights stay on? <input type="text" name="timer" value="10">seconds<br>
Your name? For Our Records <input id="name" type="text" name="user" placeholder="Your name here"<br>
<br>
<input type="submit" value="Update!" onclick="updateTable();return false;"/>
</form>

<script type="text/javascript">
 function updateTable(){
     if (!document.getElementsByTagName) return;
     tabBody=document.getElementsByTagName("tbody").item(0);
     row=document.createElement("tr");
     cell1 = document.createElement("td");
     textnode1=document.forms['leds'].elements[3].value;
     cell1.appendChild(textnode1);
     row.appendChild(cell1);
     tabBody.appendChild(row);
 }
</script>

<body>
<h1>Who has Changed Our Lights?</h1>
<table border='1' id='mytable'>
<tbody>
<tr>"This Could Be You"</tr>
</tbody>
</table>
</body>

</html>

我根本无法让表格元素出现在表格中。

javascript html forms html-table auto-populate
1个回答
1
投票

你的HTML有一些拼写错误和其他问题。您的JavaScript处于正确的轨道上,但过于复杂(通常将所有这些都放在HTML的head部分中是一种很好的做法)。这是一个可行的测试页面:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <title>Test Page</title>

  <script type="text/javascript"> <!--

 var tabBody, row, cell;
 function updateTable(){
     tabBody=document.getElementById("editable");
     row=document.createElement("tr");
     cell = document.createElement("td");
     cell.innerHTML=document.forms['leds'].elements[3].value;
     row.appendChild(cell);
     if(tabBody.childNodes.length==10)
       tabBody.removeChild(tabBody.childNodes[0])
     tabBody.appendChild(row);
 }

  // -->
  </script>
</head>
<body>

<h2>Change Our Lights:</h2>
<!-- <form name="leds" id="ledSend" method="get" target="_blank" action="https://agent.electricimp.com/Fk43xPMkSrWF"> -->
<form name="leds" id="ledSend" action="" onsubmit="return false;">
Lamp Control: <input type="radio" name="led" value="0" checked />Off
              <input type="radio" name="led" value="1" />On<br>
How long should the Lights stay on? <input type="text" name="timer" value="10" />seconds<br>
Your name? For Our Records <input id="name" type="text" name="user" placeholder="Your name here" /><br>
<br>
<input type="submit" value="Update!" onclick="updateTable();return false;"/>
</form>

<h1>Who has Changed Our Lights?</h1>

<table border='1'>
<thead><tr><th>This Could Be You</th></tr></thead>
<tbody id="editable"></tbody>
</table>

</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.