Chitika

Tuesday, October 2, 2012

Add or Update table row using javascript

Add , update and delete table row is common scenario in every web application , doing it  using JavaScript will give you good performance to your application.
Today i am putting some Javascript basic table manipulation code . 

Create Cells in a table using Javascript 
Syntax: table Object.cells




<table border="1" id="myTable">
<tbody>
<tr>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
</tbody></table>
<input onclick="cell()" type="button" value="Alert first cell">


function cell()
{
var x=document.getElementById('myTable').rows[0].cells;
alert(x[0].innerHTML);
}


Insert Row to a table through Javascript 
Syntax: tableObject.insertRow(index) 



<table border="1" id="myTable">
<tbody>
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
</tbody></table>
<input onclick="insRow()" type="button" value="Insert new row">

function insRow()
{
document.getElementById('myTable').insertRow(0)
}

Delete Row from a table through Javascript
Syntax : table Object.delete Row(index) 

<table border="1" id="myTable">
<tbody>
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
</tbody></table>
<input onclick="delRow()" type="button" value="Delete first row">

function delRow()
{
document.getElementById('myTable').deleteRow(0)
}

Hope you like it.


No comments:

Post a Comment