简体   繁体   English

JavaScript - 启用/禁用单选按钮的复选框

[英]JavaScript - Checkbox to enable/disable radio buttons

IM SO CLOSE!我很近! by default, the buttons are enabled.默认情况下,按钮处于启用状态。 also when checked both are enabled but when unchecked only one is disabled.同样,在检查两者时,都将启用两者,但是如果未选中,则仅禁用一个。

I want it so that when the check box is checked both radio buttons are enabled.我想要它,以便在选中复选框时启用两个单选按钮。 and when unchecked both radio buttons are disabled.未选中时,两个单选按钮都被禁用。

no Jquery, please没有Jquery,请

JS: JS:

var sipch = document.querySelector("input[name=sip]");
sipch.addEventListener("change", function (event) {
    if (event.currentTarget.checked) {
        document.querySelector("input[name=protocol]").removeAttribute("disabled");
    } else {
        document.querySelector("input[name=protocol]").setAttribute("disabled", "disabled");
    }
});

HTML: HTML:

<!DOCTYPE html>
<html lang="en">
    <body>
        <form id="myForm" onsubmit="goPVFive(event)" method="get">
            <div id="pBFContainer" class="container">
                <div id="bodyFOption1">
                    <input type="checkbox" name="sip" value="true">Would you like to include establishing the SIP session test?<p>
                    <input type="radio" class="testD" name="protocol" value="udp" disable/>UDP
                    <input type="radio" class="testD" name="protocol" value="tcp" disable/>TCP <label class="testD">(UDP is most Common)</label>
                </div>
                <div id="bodyFOption2">
                    <input type="checkbox" name="fWallInt" value="true">Would you include SIP ALG firewall interference test"
                    </div>
            </div>
            <input type="submit" id="subButton" value="Next..." />
        </form>
    </body>
    <script type="text/javascript" src="evalportalp1.js"></script>
</html>

Yo need to use querySelectorAll and then loop through the results, disabling/enabling each of them:你需要使用 querySelectorAll 然后遍历结果,禁用/启用它们中的每一个:

  if (event.currentTarget.checked) {
    document.querySelectorAll('input[name=protocol]')
        .forEach((elem) => elem.removeAttribute('disabled'));
  } else {
    document.querySelectorAll('input[name=protocol]')
        .forEach((elem) => elem.setAttribute('disabled', 'disabled'));
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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