'Jquery - How can I increment an id in different parent div?
In my project, I need to register ids so that when I click on a button that has a checkbox type, it only checks the button where I clicked.
In the custom-switch class, I wanted to put an id in the input and a for in the label. I managed to display the id and the for but all the input and label of each click-and-get-containerDiv class have the same id as the others.
My html code :
<div class="col-2 click-and-get-container click-and-get-containerDiv">
<div class="checkbox-container">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" value="1">
<label class="custom-control-label">Activate click & get</label>
</div>
</div>
<div class="col-12 d-none click-and-get-amount-form" id="click-and-get-amount-form_all">
<input type="number" class="form-control click-and-get-amount" value step="0.01" placeholder="Price (EUR)">
<span class="small text-danger click-and-get-amount-error d-none"></span>
</div>
</div>
For the js code, I used a for so that my incrimentation stops at the total number of gg class there are in the html page (I checked with a console.log()).
My javascript code :
for (let idClickAndGet = 1; idClickAndGet <= $('.click-and-get-containerDiv').length;) {
$(`.custom-control-input:nth-child(${idClickAndGet})`).attr('id', `click-and-get${idClickAndGet}`);
$(`.custom-control-label:nth-child(${idClickAndGet})`).attr('for', `click-and-get${idClickAndGet}`);
idClickAndGet++;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
