简体   繁体   中英

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

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:

<!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:

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

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