Skip to content
Advertisement

Javascript increase [i] when checkbox == true

I want to give IDs to divs from checkboxes which only are checked. E.g. I got 5 checkboxes and every time a checkbox has not been checked the loop should increase all upcoming checked checkboxes by 1.

function saveData() {
    for (let i = 0; i <= 4; i++) {
        document.getElementsByClassName('cb')[i].id = 'id' +i;
        let id_active = document.getElementById('id' + i);
        if (id_active.checked === true) {
            let div_id = document.getElementsByClassName('div')[i].id = 'div' + i;
            document.getElementsByClassName('div')[i].innerText = div_id;
            
        } 
        if (id_active.checked === false) {
            i += 1;
        }
    }
}    
<input type="checkbox" class="cb" checked>
<input type="checkbox" class="cb" checked>
<input type="checkbox" class="cb">
<input type="checkbox" class="cb" checked="">
<input type="checkbox" class="cb">
<br>
<br>
<button onclick="saveData()">Check</button>


<div class="div"></div>
<div class="div"></div>
<div class="div"></div>

So in this case the third div should get the id=”4″ but the loop stops after a checkbox is not checked. How can I increase i + 1 for all upcoming [i] and don’t stop the loop after the first checkbox.checked === false? A result should look like this:

enter image description here

Advertisement

Answer

@SaymoinSam can you give me an example what extra variable I need?

I meant something like this, note that I have refactored your code to a better and clean code

function saveData() {
  let divs = document.querySelectorAll(".div"), index = 0;
  document.querySelectorAll(".cb").forEach(function(input, ind) {
    if(input.checked) {
      divs[index].id = divs[index++].innerText = `div${ind}`;
    }
  });
}  
<input type="checkbox" class="cb" checked>
<input type="checkbox" class="cb" checked>
<input type="checkbox" class="cb">
<input type="checkbox" class="cb" checked="">
<input type="checkbox" class="cb">
<br>
<br>
<button onclick="saveData()">Check</button>


<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
Advertisement