选中另一个复选框后,如何检查该复选框?[JavaScript] [英] How can I check a checkbox when another checkbox is checked? [JavaScript]

查看:57
本文介绍了选中另一个复选框后,如何检查该复选框?[JavaScript]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个小表格,您可以在底部看到它.而且我想知道如何制作JavaScript函数,例如,如果我选中复选框3,那么它将同时选中复选框2和1.我已经在互联网上寻找了几个小时,而大多数东西都无法正常工作或涉及jQuery.我宁愿只使用HTML/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>

我认为您可以使用纯Javascript

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');
        }
}

这篇关于选中另一个复选框后,如何检查该复选框?[JavaScript]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆