简体   繁体   English

单选按钮的 Javascript 验证不起作用

[英]Javascript validation for radio button are not working

Suppose i have this piece of my html code假设我有这一段 html 代码

<!--Marital Status-->
            <div class="gap">
                <table>
                    <tr class="parent">
                        <td>Martial Status:</td>
                        <td>&emsp;
                            <input type="radio" id="rad1" name="Status" value="1">
                            <label for="Single">Single</label>
                            <br>&emsp;
                            <input type="radio" id="rad2" name="Status" value="2">
                            <label for="Married">Married</label>
                        </td>
                    </tr>
                </table>
            </div>

and for the javascript对于 javascript

function validateForm() {
var status = document.getElementsByName("Status");
var validradio = false;
var i = 0;
  while(!validradio && i < status.length){
    if(status[i].checked) validradio = true;
    }
    i++;

  if (!validradio){
    alert("Please select your marital status");
    return false;
  }
}

when i try the validation without checking the radio button, the page become not responsive and the alert box didn't pop up as it should.当我在不检查单选按钮的情况下尝试验证时,页面变得没有响应,并且警报框没有按应有的方式弹出。 But when i checked one of the checkbox, the page turn out just find.但是当我选中其中一个复选框时,页面结果只是找到了。 May i know, what's going on?我可以知道,这是怎么回事?

You've misaligned one statement in the javascript, change it to:您错位了 javascript 中的一条语句,将其更改为:

function validateForm() {
    var status = document.getElementsByName("Status");
    var validradio = false;
    var i = 0;
    while(!validradio && i < status.length){
        if(status[i].checked) validradio = true;
        i++;
    }
    if (!validradio){
        alert("Please select your marital status");
        return false;
    }
}

With i++ outside of the loop, i forever remained at value 0 . i++在循环之外, i永远保持在值0

This can be simplified immensly.这可以大大简化。 Use querySelectorAll with an attribute selector and the :checked pseudo class and count the resultquerySelectorAll与属性选择器和:checked伪 class 一起使用并计算结果

 function validateForm() { //Use an attribute selector with:checked to get the number of selected if (document.querySelectorAll("[name=Status]:checked").length < 1;) { alert("Please select your marital status"); return false; } } document.getElementById("validate").addEventListener("click", validateForm);
 <div class="gap"> <table> <tr class="parent"> <td>Martial Status:</td> <td>&emsp; <input type="radio" id="rad1" name="Status" value="1"> <label for="Single">Single</label> <br>&emsp; <input type="radio" id="rad2" name="Status" value="2"> <label for="Married">Married</label> </td> </tr> </table> </div> <button id="validate">Validate</button>

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

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