简体   繁体   中英

How can I check a checkbox when another checkbox is checked? [JavaScript]

So I have a little form which you can see at the bottom. And I want to know how I can make a JavaScript function where if I, for example, check checkbox 3 it will also check checkboxes 2 and 1. I have been on the internet looking for hours now and most stuff either doesn't wanna work or involves jQuery. I'd rather use HTML/JavaScript only.

I thank you for taking your time to at least read this!

<h3>HTML</h3>
    <label><input type="checkbox" name="html1" value="html1" id="html1"/><span class="label-text"></span></label>
    <label><input type="checkbox" name="html2" value="html2" id="html2"/><span class="label-text"></span></label>
    <label><input type="checkbox" name="html3" value="html3" id="html3"/><span class="label-text"></span></label>
    <label><input type="checkbox" name="html4" value="html4" id="html4"/><span class="label-text"></span></label>
    <label><input type="checkbox" name="html5" value="html5" id="html5"/><span class="label-text"></span></label>
<label><input onclick="onToggle()" type="checkbox" name="html3" value="html3" id="html3"/><span class="label-text"></span></label>

I think that way you can do it with plain Javascript

function onToggle(){
       if (document.querySelector('#html3').checked) {
          // if checked
          console.log('checked');
          document.getElementById("html2").checked = true
          document.getElementById("html1").checked = true
        } else {
          // if unchecked
          console.log('unchecked');
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM