需要帮助使用 JavaScript 验证单选按钮

Need help validating radio buttons with JavaScript

本文关键字:JavaScript 验证 单选按钮 帮助      更新时间:2023-09-26

我需要帮助验证JavaScript的单选按钮。这是HTML的部分:

<span class="formbold">Will you be attending the ceremony and reception?</span><br/>
<input type="radio" name="receptionattend" value="yesboth" /> Yes, both!<br/>
<input type="radio" name="receptionattend" value="yesc" /> Yes, but only the ceremony! <br/>
<input type="radio" name="receptionattend" value="yesr" /> Yes, but only the reception!<br/>
<input type="radio" name="receptionattend" value="no" /> No, you guys are lame!

这是我拥有的最简单的验证代码:

function validateForm()
    var y=document.forms["rsvpform"]["receptionattend"].checked;
 if (y==null || y=="")
    {
    alert("Please indicate whether or not you will attend.");
    return false;
    }
}

的问题主要是,无论我如何编码验证,即使我选择了单选按钮,它也会返回错误消息。

您遇到的第一个问题是,一般来说,您应该在单选按钮中强制使用默认值,使其中一个按钮已经"选中",并且永远不会将 null 值传递给表单检查器。大多数人希望他们的单选按钮已经选中了默认值,这是 Web 开发中的标准做法。

但是,如果您需要检查 null 或未定义,则应使用 typeof 并与 === 进行严格比较

 (typeof y === "undefined" || y === null);

阅读您的评论后 - 我注意到了另一件事。您是否尝试通过像onclick函数一样读取DOM直接从Javascript获取值?您将无法执行此操作,因为您实际上从未通过此行获得检查值。

var y=document.forms["rsvpform"]["receptionattend"].checked;

相反,请尝试这样的事情。

var y = document.getElementsByName('receptionattend');
var y_value;
for(var i = 0; i < y.length; i++){
    if(y[i].checked){
       y_value = y[i].value;
   }
}

y_value现在应该返回选中的单选按钮的结果。 如果未检查任何内容y_value则将为空。

这一行:

var y=document.forms["rsvpform"]["receptionattend"].checked;

根据元素的 checked 属性返回truefalse,因此您应该执行以下操作:

if ( !y ) { //if not checked i.e false
    alert("Please indicate whether or not you will attend.");
    return false;
}

喜欢:

function validateForm() {
    var is_checked = false;
    var eles = document.forms["rsvpform"]["receptionattend"];
    for(var i = 0; i < eles.length; i++ ) {
        if( eles[i].checked ) {
            is_checked = true;
            break;
        }
    }
    if (!is_checked)
    {
        alert("Please indicate whether or not you will attend.");
        return false;
    }
    else {
        alert("valid");
     }
}

演示:: js小提琴

我不建议为此使用 jquery。但是如果你最终使用jquery,它使这种验证变得非常容易。

HTML 请注意标签的使用,这只是一个很好的做法,这意味着您的使用可以单击文本和一大堆其他访问奖励。

<span class="formbold">Will you be attending the ceremony and reception?</span><br/>
<input type="radio" name="receptionattend" value="yesboth" id="rcBoth" /><label for="rcBoth">Yes, both!</label><br/>
<input type="radio" name="receptionattend" value="yesc" id="rcCOnly" /><label for="rcCOnly"> Yes, but only the ceremony! </label><br/>
<input type="radio" name="receptionattend" value="yesr" id="rcROnly" /><label for="rcROnly">Yes, but only the reception!</label><br/>
<input type="radio" name="receptionattend" value="no" id="rcNo" /><label for="rcNo"> No, you guys are lame!</label><br />
<input type="button" value="Validate Me" id="btnValidate"/>

Javascript/Jquery 在 jquery $(document).ready 事件中连接起来。

$("#btnValidate").click(function(){
    //The following selector is not very efficient, classes 
    //or a bounding element (eg div or fieldset) would be better
    if($("input[name='receptionattend']:checked").length == 0)
    {
        alert("Please tell us if you're attending or not!");
    }
});

http://jsfiddle.net/wpMvp/

分解脚本

  • $("#btnValidate").click(function(){});onlclick 事件处理程序添加到 ID 为 btnValidate 的按钮
  • $("input[name='receptionattend']:checked").length返回选中了多少个名称为 receptionattend 的输入元素
  • 其余的应该是仙女不言自明