Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 477
Alfred Avatar asked Mar 11 '12 19:03

Alfred


4 Answers

You can use .prepend function in jQuery.

$('#mytable').prepend($('<tr>'));

http://api.jquery.com/prepend/

like image 135
Andrei Avatar answered Nov 15 '22 23:11

Andrei


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");   
});​
like image 31
Vigrond Avatar answered Nov 15 '22 23:11

Vigrond


Using .on('click',...); and prepend: http://jsfiddle.net/k8hCa/

jQuery:

$('#but').on('click', function(e){
    $('#mytable').prepend('<tr><td>newcol1</td><td>newcol2</td><td>newcol3</td></tr>');
});
like image 27
Alex Avatar answered Nov 15 '22 22:11

Alex


The accepted answer is good, but it is definitely worth noting that the tbody is the node you should append/prepend to, and using the appendTo and prependTo methods is the best solution as it will work when there are any number of rows, including zero.

See this answer for a good example: https://stackoverflow.com/a/1353736/2812428

Note also that it is good practice to specify a tbody yourself, even if there are no rows, to avoid the issue that there would be no tbody automatically in the DOM in the case that there were no rows added to the table.

like image 36
Dan Hobbs Avatar answered Nov 15 '22 23:11

Dan Hobbs