简体   繁体   中英

how to loop in html table and change the value of each cell in javascript

I have my input table which already filled by the user. now what I am trying to do is to loop on my table and change the value of each cell td using my JavaScript. some of my cells has input field and others only have text between td tags. I loop on my table correctly and I change the values of cells that has input field using the expression table.rows[R].cells[C].children[0].value = value; but I do not know how to change the cell that has only text between td tags without input field! tried to write table.rows[R].cells[C].value = value but its not working: my table code:

var table = document.getElementById('table');
var rowCount = table.rows.length;
var colCount = document.getElementById('table').rows[0].cells.length;
for (var r = 1; r < rowCount; r++) {
    for (var c = 1; c < colCount - 1; c++) {
        table.rows[r].cells[c].children[0].value = somevalue; // this works with cells that has input field but not with cells that has not 
        table.rows[r].cells[c] value = somevalue; // tried this line but not working
    }
}

Based on your explanation I understand that you want to modify the values of all td tags (input child or text child). In your snippet there are two problems in order to achieve this:

  1. The start index of the “column loop” (c) is 1 and you loop until this index is less than the length of all columns. This means that you'll loop through all the columns except the first and last one. Maybe this is your intention.
  2. You have a syntax error in the last line of the last for loop.

For your “main” problem, it seems like you are treating the cells the same even though some contain input elements and some text nodes. You can simply solve this by adding some logic and depending on if the cell has children (an input field) or not (text-node) you treat it respectively. For text nodes we simply modify the innerHTML.

Here's a snippet which should do the job for you if I understood you correctly:

var table = document.getElementById("table");
var rowCount = table.rows.length;
var colCount = document.getElementById("table").rows[0].cells.length;

var somevalue = "modified value";

for (var r = 1; r < rowCount; r++) {
  
  for (var c = 0; c < colCount; c++) {
    const cell = table.rows[r].cells[c];

    if (cell.children.length) {
      cell.children[0].value = somevalue;
    } else {
      cell.innerHTML = somevalue;
    }

  }
}

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