I am working on dynamically updating the id
values of elements using JQuery/CSS selectors in a loop.
My goal is to have the click event on a button trigger a for loop that updates the id
attribute of each
<div id='input_1' class="input row">
within the button_pro
class.
The problem I am encountering is that I am unable to select and update my child IDs as the loop runs.
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!