jeudi 3 mai 2018

trigger event if checkbox is checked javascript

I have an HTML page with several checkboxes and one disabled button. Now, as soon as one of the checkboxes or more are checked, the button must enable. Also, when all the checkboxes are unchecked, the button must go to disable-state again. The test case seems to be: if a checkbox is checked, then the button should enable (this I can get to work). Then, if another checkbox is checked, the button remains enabled (this also works). If the first checkbox is unchecked, the button must also stay enabled, bceause the 2nd checkbox is still checked. It is this that I can't seem to work. The checkboxes are dynamical of nature, so I can't define them beforehand. There might be two, or ten. This is why I tried a for loop.

I can't get this to work, what I have so far:

var x = document.getElementsByName("cb");

for (var i = 0; i < x.length; i++) {
    if(x[i].checked == true){
            document.getElementById('Button1').disabled=false
    }
} 
<div class="container">
   <input type="button disabled" name="Button1" class="inputButton" id="Button1" value=" Send " disabled="disabled" />
</div>
<div>
   <input type="checkbox"  onchange="document.getElementById('Button1').disabled = !this.checked;" />
   <input type="checkbox"  onchange="document.getElementById('Button1').disabled = !this.checked;" />
</div>
Both with the HTML and onchange event and the Javascript I can't get it to work. The two are not used at the same time.


Aucun commentaire:

Enregistrer un commentaire