简体   繁体   中英

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. First I make a new variable called oldtable , and then split it at each <tr> .. and save that to the array 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.

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. Make sure your table has a TBODY element and give it an 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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