<article id="mission">
<img src="https://blog.kakaocdn.net/dn/TfNOJ/btqNXGzXt1z/1Zlb8W1gitIt6WOPWS7z3k/img.gif" width="100%" />
</article>
<article id="container">
<button></button>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</article>
<script src="./main.js"></script>
let inputlist = document.querySelectorAll('input');
let button = document.querySelector('button');
let save = 0;
let num = 0;
button.addEventListener('click',()=>{
for(let i = 0; i< 4; i++){
inputlist[(i+save)%14].checked = true;
}
num++;
if(save-1 != -1){
if(inputlist[(save-1)%14].checked == true){
inputlist[(save-1)%14].checked =false;
}
}
save++;
});
When I run the code, it doesn't work any more than 7-8 clicks. When you enter the link in the body, the first input element should behave like the image that appears.
But I get the error TypeError: Cannot set properties of undefined (setting 'checked') and it doesn't work anymore.
Why?
You have 13 inputs so it should be mod 13 not 14. Check the snippet below
let inputlist = document.querySelectorAll('input');
let button = document.querySelector('button');
let save = 0;
let num = 0;
button.addEventListener('click',()=>{
for(let i = 0; i < 4; i++){
inputlist[(i + save) % 13].checked = true;
}
num++;
if(save - 1 !== -1){
if(inputlist[(save - 1) % 13].checked === true){
inputlist[(save - 1) % 13].checked = false;
}
}
save++;
});
<article id="mission">
<img src="https://blog.kakaocdn.net/dn/TfNOJ/btqNXGzXt1z/1Zlb8W1gitIt6WOPWS7z3k/img.gif" width="100%" />
</article>
<article id="container">
<button>Move</button>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</article>
Looking at your code, you're using %14, but you only have 12 input elements on the page. When the code is running through the loop you run out of elements. The solution is to either change your %14 to %12 or to add in an additional two input elements.
The other option if you're going to add checkboxes would be to use %inputlist.length. This would avoid needing to count how many input elements in your html file.