Reputation: 1031
Please I have the following markup :
<div class="closet">
<input name="hello1" class="input" />
</div>
<div class="closet">
<input name="hello2" class="input" />
</div>
and I want to attribute the input name and set another value (example hello5 and hello6) , so this is my code :
var i = 5;
$('.closet').each(function (k)
{
i++;
$('.input').attr('name', 'hello'+i);
});
But the problem it gave me for both inputs the value "hello6".
Please have you any advise ?
Upvotes: 0
Views: 4681
Reputation: 55740
Instead of
$('.input').attr('name', 'hello'+i);
Should be
$(this).find('.input').attr('name', 'hello'+i);
Upvotes: 0
Reputation: 318182
You already have access to both an index and the element inside the each()
loop:
$('.closet').each(function(index, elem) {
$('.input', elem).attr('name', 'hello'+(index+5));
});
Upvotes: 0
Reputation: 382132
Replace
$('.input').attr('name', 'hello'+i);
with
$('.input', this).attr('name', 'hello'+i);
so to change the .input
that is inside the .closet
on which your iteration is.
Upvotes: 2