简体   繁体   中英

Javascript: Triggering “for” loop using “if…else” statements not working

I am trying to make a simple script which automatically blocks the input boxes in the file when I tick a checkbox. For this, I am trying to add/remove the "disabled" attribute by triggering a loop every time the checkbox is clicked. Looks something like this:

 function locker() { var boxes = document.querySelectorAll("input[type='text']"); var x = getElementById("lock") for (i = 0; i < inputBoxes.length; i++) { if (x.checked == true) { boxes[i].disabled = true; } else { boxes[i].disabled = false; } } } 
 <input type="checkbox" id="lock" onClick="locker()"> <input type="text"></input> <input type="text"></input> <input type="text"></input> 

However, I can't seem to get it to work. I don't have much experience coding, and I feel like I am making a very basic mistake, but I couldn't find a solution to this problem so far... How can I solve this? Are there any other workarounds to get the same result?

Thanks in advance

You need to use document.getElementById("lock") instead of getElementById("lock") and use the correct variable names for your variables. You used inputBoxes and boxes while you meant to use the same variable.

 function locker() { var inputBoxes = document.querySelectorAll("input[type='text']"); var x = document.getElementById("lock") for (i = 0; i < inputBoxes.length; i++) { if (x.checked == true) { inputBoxes[i].disabled = true; } else { inputBoxes[i].disabled = false; } } } 
 <input type="checkbox" id="lock" onClick="locker()"> <input type="text"></input> <input type="text"></input> <input type="text"></input> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM