Reputation: 5810
I am trying to update the id
values of elements using JQuery/CSS selector dynamically by running a for
loop.
What i want is when i click on button it runs the for loop and updates the id
of <div id='input_1' class="input row">
which is inside each button_pro class
.
My issue is i cannot do so, i am not able to select child as for loop executes and can not update my id values.
HTML
<div class="button_pro">
<div id='input_1' class="input row">
<div class="input-field col s1">
<input class="sno" type="text" name="Sr_1" value="1">
<label for="Sr">Sr</label>
</div>
<div class="input-field col s2">
<input id="item_code" type="text" name="item_code_1" value="">
<label for="item_code">Item Code</label>
</div>
</div>
</div>
<div class="button_pro">
<div id='input_1' class="input row">
<div class="input-field col s1">
<input class="sno" type="text" name="Sr_1" value="1">
<label for="Sr">Sr</label>
</div>
<div class="input-field col s2">
<input id="item_code" type="text" name="item_code_1" value=" ">
<label for="item_code">Item Code</label>
</div>
</div>
</div>
<br>
<button>Click</button>
JQuery/JavaScrit
$(function () {
$('button').click(function () {
var numof = $(".input").length;
alert(numof);
var i;
for (i = 1; i <= numof; i++)
{
$(".input:nth-child(" + i + ")").attr('id', 'input_' + i);
}
});
});
Thank You!
Upvotes: 1
Views: 194
Reputation: 11
$(window).load(function() {
$(function() {
$('button').click(function() {
var objs = $(".input");
var numof = $(".input").length;
alert(numof);
/*
var i;
for (i = 1; i <= numof; i++) {
$(".input:nth-child(" + i + ")").attr('id', 'input_' + i);
}
*/
$(objs).each(function(i, item) {
$('#' + item.id).attr('id', 'input_' + i);
});
});
});
}); //]]>
Upvotes: 0
Reputation: 87203
Use eq()
.
:nth-child
will select the nth
child. As your elements are not direct child, use eq
.
$(".input").eq(i).attr('id', 'input_' + i);
Also, note that eq
starts from zero, so you need to change the for
loop.
$(function() {
$('button').click(function() {
var numof = $(".input").length;
alert(numof);
var i;
for (i = 1; i <= numof; i++) {
$(".input:nth-child(" + i + ")").attr('id', 'input_' + i);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="button_pro">
<div id='input_1' class="input row">
<div class="input-field col s1">
<input class="sno" type="text" name="Sr_1" value="1">
<label for="Sr">Sr</label>
</div>
<div class="input-field col s2">
<input id="item_code" type="text" name="item_code_1" value="">
<label for="item_code">Item Code</label>
</div>
</div>
</div>
<div class="button_pro">
<div id='input_1' class="input row">
<div class="input-field col s1">
<input class="sno" type="text" name="Sr_1" value="1">
<label for="Sr">Sr</label>
</div>
<div class="input-field col s2">
<input id="item_code" type="text" name="item_code_1" value=" ">
<label for="item_code">Item Code</label>
</div>
</div>
</div>
<br>
<button>Click</button>
Upvotes: 2