views:

48

answers:

3

How to loop through all inputs inside a tr and set attribute(id and name) with JQuery

+3  A: 
$("tr input").each(function()
{
     $(this).attr("id", .....);
     $(this).attr("name", .....);
});
James Curran
+1 so fast.....
kekekela
+1  A: 

This could be done in one go:

$('tr input').attr({
    'id': 'new_id',
    'name': 'new_name'
});

But since id's are supposed to be unique this is probably not what you want to do. Here's a better approach:

$('tr input').attr({
    'id': function (index, attr) { return 'new_id-' + index },
    'name': function (index, attr) { return 'new_name-' + index }
});

This will change your input's id and name like this:

<tr>
    <td><input type="text" id="new_id-0" name="new_name-0"></td>
</tr>
<tr>
    <td><input type="text" id="new_id-0" name="new_name-1"></td>
</tr>
<tr>
    <td><input type="text" id="new_id-0" name="new_name-2"></td>
</tr>

You can find more info in API docs for attr().

Ihor Kaharlichenko
A: 

From http://stackoverflow.com/questions/3479474

$(function() {
    $('#table tr').each(function(index, element)
    {
       var e = $(element);
       e.find('td:eq(0)').text(index);
       var first = 'txtCollectionText' + index.toString();
       var second = 'txtLink' + index.toString();
       e.find('td:eq(1) input').attr({name: first, id: first});
       e.find('td:eq(2) input').attr({name: second, id: second});
    });
}

If placed inside a script tag, this code will automatically execute as soon as the document is finished being constructed by the browser. That's what the $(function() {}) notation does -- it's shorthand for $(document).bind('ready', function() {}).

Ian Henry