Add row to top of table - JavaScript - jQuery

What is the best method in jQuery to add an extra 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 top of the table with the given default values. How can I accomplish this using JavaScript and jQuery? The violin will be useful.

+4
source share
5 answers

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"); });​ 
+7
source

You can use the .prepend function in jQuery.

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

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

+14
source

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>'); }); 
+5
source

The accepted answer is good, but it is definitely worth noting that tbody is the node to which you have to add / add, and using the appendTo and prependTo methods is the best solution, since it will work when there is any line number, including zero.

See this answer for a good example: fooobar.com/questions/118121 / ...

Also note that it is good practice to specify the tel yourself, even if there are no rows, in order to avoid the problem that would automatically prevent a person in the DOM if there were no rows in the table.

+1
source

Folloing is what I do

Template

 <script type="text/template" id="cardTemplate"> <TR class=Normal> <TD> {0} </TD> <TD> {1} </TD> <TD> {2} </TD> </TR> </script> 

JQuery

  String.prototype.format = function() { var args = arguments; return this.replace(/{(\d+)}/g, function(match, number) { return typeof args[number] != 'undefined' ? args[number] : match ; }); }; var cardTemplate = $("#cardTemplate").html(); //Note: format is a custom method added for "String" var template = cardTemplate.format("a", "b","c"); //$('#tblScanResult tbody > tr:first').before(template); $('#tblScanResult tbody').prepend(template); 
0
source

Source: https://habr.com/ru/post/1400871/


All Articles