Search code examples
javascriptfor-loopif-statementcheckboxdisabled-input

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


Solution

  • 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>