简体   繁体   English

使用JavaScript轻松设置字段值

[英]Easily setting field values with JavaScript

Wasn't really sure how to ask the question, but my situation is this... I have a table with one row, which contains a few input boxes. 真的不确定如何问这个问题,但是我的情况是……我有一张表,其中有一行,其中包含一些输入框。 When a user presses the add new , I have managed to add another row to the table. 当用户按下add new ,我设法将另一行添加到表中。 First I make a new variable called oldtable , and then split it at each <tr> .. and save that to the array rows . 首先,我创建一个名为oldtable的新变量,然后在每个<tr> ..处将其拆分,然后将其保存到数组rows I use this code: 我使用以下代码:

var newdata="";
  for(i=0;i<rows.length;i++)
  {
   // adds the next row on...
   newdata=newdata+rows[i]+"<tr>";
  }

  newdata=newdata+"MY NEW ROW GOES HERE!";

Then I go on to reset the table innerHTML to the newdata variable. 然后,我继续将表innerHTML重置为newdata变量。

All works fine, until the user enters data in the first row, and then goes to add data in the second. 一切正常,直到用户在第一行中输入数据,然后在第二行中添加数据。 Then the values on the first row are gone, understandably. 可以理解,然后第一行的值消失了。 Taking into account that the table can theoretically have as many rows as the user wants, how can I go about keeping the values of the first row intact? 考虑到该表理论上可以具有用户想要的尽可能多的行,我该如何保持第一行的值不变? Is there a way to insert data into the table without reseting what's there? 有没有一种方法可以将数据插入表中而不重置其中的内容?

Thanks. 谢谢。

var olddata = document.getElementById("products_table").innerHTML;

// This splits up each row of it
var rows = olddata.split("<tr>");

// Makes a variable where the new data is going to be stored
var newdata = "";

// This loop is to add back the existing html into the table, it is one short, because we Omit the "add new product" row.
for(i=0;i<rows.length-1;i++)
{
  // adds the next row on...
  newdata=newdata+rows[i]+"<tr>";
}

// Adds the additional html needed to 
newdata=newdata+"my new row goes here!";

// Add newly edited table back in...
document.getElementById("products_table").innerHTML=newdata;

Instead of manipulating HTML in string form (very error prone), you should use the built-in DOM manipulation methods to add new rows to your table. 不要使用字符串形式的HTML(非常容易出错),而应该使用内置的DOM操作方法向表中添加新行。 Make sure your table has a TBODY element and give it an ID: 确保您的表具有TBODY元素并为其指定ID:

<table id = "product_table">
 <tbody id = "product_table_tbody">
  <tr>
   <td>A Cell</td>
  </tr>
 </tbody>
</table>

Then, attach an event handler to the Add Row button and do something like this: 然后,将事件处理程序附加到“添加行”按钮,然后执行以下操作:

function addRow() {
   var myTbody = document.getElementById("products_table_tbody");
   var myRow = document.createElement("tr");
   var myCell = document.createElement("td");

   myCell.innerHTML = "My new cell";
   myTbody.appendChild(myRow);
   myRow.appendChild(myCell);
}

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

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