yossi
yossi

Reputation: 296

How to insert unique id to each input tag?

I try to add unique id to each input tag from a generated table code. DEMO I want code like this :

<table>
<tbody>
<tr>
<td class="tableCell">
<input id="1"> </input>
</td>
<td class="tableCell">
<input id="2"> </input>
</td>
</tr>
<tr>
<td class="tableCell">
<input id="3"> </input>
</td>
<td class="tableCell">
<input id="4"> </input>
</td>
</tr>
</tbody>
</table>

instead

<table>
<tbody>
<tr>
<td class="tableCell">
<input>
</td>
<td class="tableCell">
<input>
</td>
</tr>
<tr>
<td class="tableCell">
<input>
</td>
<td class="tableCell">
<input>
</td>
</tr>
</tbody>
</table>

the function which generate the code :

function createDynamicTable(tbody, rows, cols) {
    if (tbody == null || tbody.length < 1) return;
    for (var r = 1; r <= rows; r++) {
        var trow = $("<tr>");
        for (var c = 1; c <= cols; c++) {
            var input = $("<input />");
            $("<td>").addClass("tableCell").append(input).appendTo(trow);
        }
        trow.appendTo(tbody);
    }
}

createDynamicTable($("tbody"), 2, 2);

How can I make the change to insert uniq id to each input tag?

Upvotes: 0

Views: 127

Answers (2)

thecodeparadox
thecodeparadox

Reputation: 87073

for (var c = 1; c <= cols; c++) {
    var input = $("<input />");

    // but don't use only numeric id
    input.attr("id", c);

    // OR
    var input = $("<input />", {id: c});

    $("<td>").addClass("tableCell").append(input).appendTo(trow);

    // better would be
    var input = $("<input />", {id: "id_" + c});

    // OR
    input.attr("id", "id_" + c);

    $("<td>").addClass("tableCell").append(input).appendTo(trow);
}

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318488

Outside the function:

var currentId = 0;

In your function:

var input = $("<input />", {id: 'inp-' + ++currentId});

Replace inp- with whatever you like, but an ID cannot start with a number .

Upvotes: 2

Related Questions