Skip to content Skip to sidebar Skip to footer

Jquery Dynamically Created Table Need To Add Id's Dynamically To 's

I have created a table using jQuery as follows: $('#dynamictable').append(''); var table = $('#dynamictable').children(); for (var i = 0; i < 13; i++) { var str

Solution 1:

You can try this also -

var id = 0;
for (var i = 0; i < 13; i++) {
    var str = "<tr>";
    for (var j = 0; j < 7; j++) {
        str += "<td id='" + id + "' style='background:#ccc;'>cell</td>";
        id++;
    }
    str += "</tr>";
    table.append(str);
}

FIDDLE

Solution 2:

You can use the below code

$('#dynamictable').append('<table>');
var table = $('#dynamictable').children();
var count = 0;
for (var i = 0; i < 13; i++) {

    var str = "<tr>";
    for (var j = 0; j < 7; j++) {
        count = count + 1;
        str += "<td style='background:#ccc;' id='td_id_"+count+"'>cell</td>";
    }
    str += "</tr>";
    table.append(str);
}
$('#dynamictable').append('</table>');

Solution 3:

Well, the simplest way I would do it is like this:

var index=0;
$("#dynamictable table td").each(function(){
    $(this).attr("id", index++);
});

Here is the update JSFiddle

In the JSFiddle, clicking on the button adds ids to the tds, you may check it in the inspect-element view :)

Post a Comment for "Jquery Dynamically Created Table Need To Add Id's Dynamically To

's"