Martes, Oktubre 6, 2015

How to Add Cells of a Table through Javascript

Hi All!

Having problems in adding table cells dynamically?. Here's how.

Create your table and button for adding cells.

<table id="myTable">
           <tr>
          <td><strong>Title</strong></td>
          </tr>
</table>

<button onClick="AddCell()">Add Cell</button>

Then write the code below in your JavaScript script:

 function addCell() {
                var rowCount = document.getElementById('myTable').rows.length;
var table = document.getElementById("myTable");
var row = table.insertRow(rowCount);
                var cell1 = row.insertCell(0);
                 cell1.innerHTML = '<strong>Title</strong>';

}

And that's it.

You can also add class or id of the row by adding:
 row.id = 1
row.className = "class"

Or if your adding textboxes or any other form elements you can write:
cell1.innerHTML = '<input type="text" value="">';
cell1.innerHTML = '<select name="select1"><option value="Hi">Hi</option></select>';

Hope That helps!

Goodluck.

Walang komento:

Mag-post ng isang Komento