Osa Osa - 1 month ago 8
HTML Question

jQuery append two tds' in one tr

How to use jQuery to append only two tds' in a single tr ..

I have a table .. I want to max how many tds per row.. 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


it's not a loop, it appends on click, so let's say I clicked 5 times, I should get this

<tr>
<td>Someting</td>
<td>Someting</td>
</tr>
<tr>
<td>Someting</td>
<td>Someting</td>
</tr>
<tr>
<td>Someting</td>
</tr>

Answer

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/

Comments