繁体   English   中英

如何检查单选按钮是否被选中?

[英]How to check if radio button is selected?

我先说这个问题,我对 JavaScript 的了解非常有限,而且我不是开发人员。 我被要求帮助为我的公司建立一个价格计算器向导。

我从 W3 Schools ( https://www.w3schools.com/howto/howto_js_form_steps.asp ) 中找到了一些代码来创建一个检查每个输入字段是否为空的表单。 我想更改代码以检查是否已选择每个组中的单选按钮。

我不确定如何更改这行代码

if (y[i].value == "")

使其检查是否已选择单选按钮。

下面是我的一个广播组和检查输入字段是否为空的脚本。

如果您想查看完整代码,请将 go 转到上面的 W3 Schools 链接。

 <div class="tab">Option 1:
    <p><input type="radio" id="male" name="gender" value="male" oninput="this.className = ''"><label for="male">Male</label></p>
    <p><input type="radio" id="female" name="gender" value="female" oninput="this.className = ''"><label for="female">Female</label></p>
  </div>      

function validateForm() {
        // This function deals with validation of the form fields
        var x, y, i, valid = true;
        x = document.getElementsByClassName("tab");
        y = x[currentTab].getElementsByTagName("input");
        // A loop that checks every input field in the current tab:
        for (i = 0; i < y.length; i++) {
          // If a field is empty...
          if (y[i].value == "") {
            // add an "invalid" class to the field:
            y[i].className += " invalid";
            // and set the current valid status to false:
            valid = false;
          }
        }
        // If the valid status is true, mark the step as finished and valid:
        if (valid) {
          document.getElementsByClassName("step")[currentTab].className += " finish";
        }
        return valid; // return the valid status
      }

检查所有单选按钮是否被选中:

 const radioButtons = Array.from(document.querySelectorAll('input[type=radio]')); function checkChecked(){ console.log(radioButtons.every(button => button.checked)); } radioButtons.forEach(button => button.onchange = checkChecked);
 <input type=radio /> <input type=radio /> <input type=radio /> <input type=radio /> <input type=radio />

LVL 2:检查所有单选按钮组至少有一个检查:

 const groupNames = ['group1', 'group2', 'group3']; const radioButtons = Array.from(document.querySelectorAll('input[type=radio]')); function checkChecked(){ console.log(groupNames.every(group => document.querySelector(`input[name=${group}]:checked`) )); } radioButtons.forEach(button => button.onchange = checkChecked);
 <input name="group1" type=radio /> <input name="group1" type=radio /> <input name="group1" type=radio /> <br/> <input name="group2" type=radio /> <input name="group2" type=radio /> <br/> <input name="group3" type=radio /> <input name="group3" type=radio />

暂无
暂无

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

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