Dan
Dan

Reputation: 235

Enable/Disable group of form input elements with a checkbox

I want a checkbox that can enable (when checked) or disable (when unchecked) a group of input form elements. I have managed to do it with only one single element but I am struggling to do it with several elements. Here is my code:

Javascript:

function myFunction() {

var elements = document.getElementsByClassName("child1");
var el = document.getElementById("myCheck");

for(var i=0; i<elements.length; i++) {

 if(el.checked) {
    elements[i].removeAttribute("disabled");
    } else {
    elements[i].setAttribute("disabled","disabled");
    }
}
}

HTML

<input type="checkbox" id="myCheck" onChange="myFunction()">Click the button to disable the form input elements<br>


<input type="radio" class="child1" name="group1" disabled="disabled">
<input type="radio" class="child1" name="group1" disabled="disabled">
<input type="radio" class="child1" name="group1" disabled="disabled">
<br>
<input type="radio" class="child1" name="group2" disabled="disabled">
<input type="radio" class="child1" name="group2" disabled="disabled">
<input type="radio" class="child1" name="group2" disabled="disabled">
<br>
<input type="text" class="child1" disabled="disabled">

(I have used getElementsByClassName as I understand that you can only have one ID by html page (i.e. getElementById would not work)).

JSFIDDLE https://jsfiddle.net/w2992L1y/

Upvotes: 4

Views: 5882

Answers (1)

Prerak Sola
Prerak Sola

Reputation: 10009

The disabled attribute does not have a value associated with it. So to disable an input element you only need to do <input disabled>. Similarly to enable/disable the input element using JavaScript you need to do:

element.disabled = true;  //disable
element.disabled = false;  //enable

For your example you could do like below:

function myFunction() {

  var elements = document.getElementsByClassName("child1");
  var el = document.getElementById("myCheck");

  for (var i = 0; i < elements.length; i++) {
    if (el.checked) {
      elements[i].disabled = true;
    } else {
      elements[i].disabled = false;
    }
  }
}
<input type="checkbox" id="myCheck" onChange="myFunction()">Click the button to disable the form input elements
<br>

<input type="radio" class="child1" name="group1">
<input type="radio" class="child1" name="group1">
<input type="radio" class="child1" name="group1">
<br>
<input type="radio" class="child1" name="group2">
<input type="radio" class="child1" name="group2">
<input type="radio" class="child1" name="group2">
<br>
<input type="text" class="child1">

Here's the working fiddle of the same: https://jsfiddle.net/prerak6962/g96j4g7g/2/

Upvotes: 4

Related Questions