add rows to table with JavaScript

后端 未结 2 546
既然无缘
既然无缘 2021-01-29 09:41

I am trying to use JavaScript or ASP C# to add rows to a table in form when the user clicks the add row button. I have working code in JavaScript. I want to add the rows with te

相关标签:
2条回答
  • 2021-01-29 10:20

    Here's how you could do that. (Obviously you can style the text boxes however you want.) Your code added the rows; I just added a textarea in each cell.

    function addrow() {
         var tableRef = document.getElementById('tbl').getElementsByTagName('tbody')[0];
         var rowcount = tableRef.rows.length;
         window.alert(rowcount);
         var newRow   = tableRef.insertRow(tableRef.rows.length);
         var textBox = "<textarea></textarea>";
         
         // Insert a cell in the row at index 0
         var tagcell  = newRow.insertCell(0);
         var desccell = newRow.insertCell(1);
         var loccell  = newRow.insertCell(2);
         var Namecell = newRow.insertCell(3);
         var Sigcell  = newRow.insertCell(4);
    
         tagcell.innerHTML = textBox;
         desccell.innerHTML= textBox;
         loccell.innerHTML = textBox;
         Namecell.innerHTML= textBox;
         Sigcell.innerHTML = textBox;
    
      }
    <table id=tbl>
        <tr>
            <td id=tag_no>Col1</td>
            <td id=desc> Col2</td>
            <td id=loc> col3</td>
            <td id=nme> col4</td>
            <td id=sig> col5</td>
        </tr>
    </table>
    <input type="button" value="clickme" onclick="addrow()" />

    EDIT: Your row count shows the correct number now. (It was only showing 1 each time before.)

    0 讨论(0)
  • 2021-01-29 10:36
    function addrow() {
        var myTable = document.querySelector('#tbl');
        var row = myTable .insertRow(0);
        var cell1 = row.insertCell(0);
        cell1.innerHTML = 'My first cell';
    
        // and so on for other cells
    }
    

    p.s. please add "" to all your HTML attributes values. For example

    <table id="tbl">
    
    0 讨论(0)
提交回复
热议问题