Reputation: 1543
I have my HTML like this
<table>
<tr>
<td>
<select>
<option>12AM</option>
<option>11PM</option>
</select>
</td>
<td>
<select>
<option>12AM</option>
<option>11PM</option>
</select>
</td>
</tr>
</table>
I want to assign an id attribute to select tag inside each tr. The following jquery does not seem to work
function addRow()
{
var rowCount = 0;
$('#SHourDivTable tr').each(function() {
if(rowCount != 0)
{
console.log($(this).html());
$(this).add("select:eq(0)").attr("id", rowCount);
$(this).add("select:eq(1)").attr("id", rowCount);
}
rowCount = rowCount + 1;
});
}
When i run this, the id attribute gets assigned to tr rather than select tag.
Upvotes: 1
Views: 86
Reputation: 16932
This will add the id 1,2 to your select elements. You had an extra in your mark up also remember that ids must be unique! id's 1 and 2 are also bad ids - select1, select2 etc would be better.
I added the id SHourDivTable to your table as I believe that was your intention.
$('#SHourDivTable tr select').each(function(i,select) {
$(select).attr('id','select'+i);
});
Upvotes: 1
Reputation: 56439
IDs must be unique. They also shouldn't start with a number. You should use data
attributes to do that.
I've also used table
instead of #SHourDivTable
, as I can't see a table with that ID in your markup.
Lastly, you need find
not add
for what you're doing here.
Try this:
function addRow()
{
var rowCount = 0;
$('table tr').each(function() {
if(rowCount != 0)
{
$(this).find("select:eq(0)").data("rowNumber", rowCount);
$(this).find("select:eq(1)").data("rowNumber", rowCount);
}
rowCount = rowCount + 1;
});
}
Upvotes: 2