How can i disable multiple inputs with JS?

Viewed 262

I tried this

  <body>
    <input placeholder="test1" class="input"/>
    <input placeholder="test2" class="input"/>
  </body>
  <script>
       document.querySelector(".input").disabled = true;
  </script>

enter image description here

Why is the second input (test2) not disabled. Thanks!

3 Answers

document.querySelector only selects the first instance of what your searching for, you need to use document.querySelectorAll('input') to select all the instances of your inputs, which returns an array you can go through,

var inputs = document.querySelectorAll('.input')
for (let i = 0;i<inputs.length;i++) {
  inputs[i].disabled = true
}

Alternatively use ForEach

var inputs = document.querySelectorAll('.input')
inputs.forEach((input)=>{
  input.disabled = true
})

Try querySelectorAll

Run the snippet below:

var allinputs = document.querySelectorAll('.input');
for (var i = 0, len = allinputs.length; i<len; i++){
    allinputs[i].disabled = true;
}
<input class="input"></input>
<input class="input"></input>

if you wrap the inputs in a <fieldset> ... </fieldset> tag and set the disabled attribute on that <fieldset disabled> - all children inputs will be disabled .

input:disabled {
 cursor: not-allowed;
}
  <fieldset disabled>
    <legend>Fieldset disabled - causes all children inputs to be disabled:</legend>
    <label for="fname">First name:</label>
    <input type="text" id="fname" name="fname"><br><br>
    <label for="lname">Last name:</label>
    <input type="text" id="lname" name="lname"><br><br>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email"><br><br>
    <label for="birthday">Birthday:</label>
    <input type="date" id="birthday" name="birthday"><br><br>
    <input type="submit" value="Submit">
  </fieldset>
  
  <hr/>
    <fieldset>
    <legend>Fieldset not disabled:</legend>
    <label for="fname">First name:</label>
    <input type="text" id="fname" name="fname"><br><br>
    <label for="lname">Last name:</label>
    <input type="text" id="lname" name="lname"><br><br>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email"><br><br>
    <label for="birthday">Birthday:</label>
    <input type="date" id="birthday" name="birthday"><br><br>
    <input type="submit" value="Submit">
  </fieldset>

Related