lundi 17 juillet 2017

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 http://ift.tt/2uvvPHU




Aucun commentaire:

Enregistrer un commentaire