JQuery adds two tds' to one tr

How to use jQuery to add only two tds' to one tr ...

I have a table. I want the maximum number of tds per line .. something like this

if($("td").length) == 0){ // get the count of existing tds $("table").append("<tr>"); } $("table").append("<td>Something</td>"); if($("td").length) == 2){ // if it hit two tds' in this tr then close the tag $("table").append("</tr>"); } // this is not a valid example, just trying to deliver my point 

this is not a loop, it is added on click, so let's say I pressed 5 times, I have to get this

 <tr> <td>Someting</td> <td>Someting</td> </tr> <tr> <td>Someting</td> <td>Someting</td> </tr> <tr> <td>Someting</td> </tr> 
+4
source share
3 answers

Let's try this:

 var max = 2 var tr = $("table tr:last"); if(!tr.length || tr.find("td").length >= max) $("table").append("<tr>"); $("table tr:last").append("<td>hi</td>"); 

http://jsfiddle.net/5yLrE/

+8
source

If $("td").length is equal, create a new line; if not, add to the last line:

 var $tds = $('table td'); var $target = $tds.last().parent(); if($tds.length % 2 === 0){ $target = $('<tr />').appendTo('table > tbody'); } $target.append("<td>Something</td>"); 
+1
source
 $('bla').click(function() { if ($('td').length % 2) === 0) $('table').append('<tr />'); $('table:last').append($('<td>Something</td>')); }); 
0
source

All Articles