blasteralfred Ψ blasteralfred Ψ - 6 months ago 18
jQuery Question

Add row to the beginning of a table - JavaScript - jQuery

What is the best method in jQuery to add an additional row to a table as the first row?

I have a table like this

<table id="mytable" cellpadding="0" cellspacing="0">
<tr>
<td>col1</td>
<td>col2</td>
<td>col3</td>
</tr>
<tr>
<td>col1</td>
<td>col2</td>
<td>col3</td>
</tr>
</table>
<button id="but">mybutton</button>


I want to add a row as the first row to the beginning of the table with given default values. How can I accomplish this using JavaScript and jQuery? A fiddle will be helpful.

Answer

http://jsfiddle.net/32Ymw/

$("#but").click(function(){
   row = $("<tr></tr>");
   col1 = $("<td>col1</td>");
   col2 = $("<td>col2</td>");
   col3 = $("<td>col3</td>");
   row.append(col1,col2,col3).prependTo("#mytable");   
});​
Comments