简体   繁体   English

需要帮助以JavaScript验证单选按钮

[英]Need help validating radio buttons with JavaScript

I need help validating radio buttons with JavaScript. 我需要帮助以JavaScript验证单选按钮。 Here's the section of HTML: 这是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!

And here's the simplest validation code I have: 这是我拥有的最简单的验证代码:

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

My issue mostly seems to be that, no matter how I code the validation, it returns an error message even when I have a radio button selected. 我的问题似乎主要是,无论我如何编码验证,即使我选择了单选按钮,它也会返回一条错误消息。

The first issue you have is that in general, you should force a default in your radio buttons, make one of the buttons be already "checked" and you will never have a null value passed to your form checker. 您遇到的第一个问题是,通常,您应该在单选按钮中强制使用默认值,使其中一个按钮已经被“选中”,并且永远不会将空值传递给表单检查器。 Most people expect their radio buttons to have a default already checked and this is standard practice in web development. 大多数人希望其单选按钮已被选中为默认值,这是Web开发中的标准做法。

However, should you need to check for null or undefined, you should use typeof and strict comparison with === 但是,如果需要检查是否为null或undefined,则应使用typeof并使用===进行严格比较

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

After reading your comment - I noticed one other thing. 阅读您的评论后-我注意到了另一件事。 Are you trying get get the value directly from Javascript by reading the DOM with like an onclick function? 您是否正在尝试像onclick函数那样通过读取DOM直接从Javascript获取值? You won't be able to do this because you aren't ever actually getting your checked value with this line. 您将无法执行此操作,因为您实际上从未通过此行获得检查值。

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

Instead, try something like this. 而是尝试这样的事情。

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 should now return the result of the checked radio button. y_value现在应该返回选中的单选按钮的结果。 If nothing was checked y_value will be null. 如果未进行任何检查,则y_value将为null。

this line: 这行:

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

returns either true or false based on checked attribute of your element, so you should be doing: 根据元素的checked属性返回truefalse ,因此您应该这样做:

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

do like: 喜欢:

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

Demo:: jsFiddle 演示:: jsFiddle

I'm not going to suggest using jquery just for this. 我不会建议仅为此使用jquery But should you end up using jquery, it makes this kind of validation very easy. 但是,如果您最终使用了jquery,它会使这种验证非常容易。

HTML Note the use of Labels, this is just a good practice, it means your uses can click on the text and a whole raft of other accesibililty bonuses. HTML注意Labels的使用,这只是一个好习惯,这意味着您的使用可以单击文本,以及其他各种可享受的好处。

<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 Wire this up in the jquery $(document).ready event. 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/ http://jsfiddle.net/wpMvp/

To break down the script 分解脚本

  • $("#btnValidate").click(function(){}); adds an onlclick event handler to the button with ID btnValidate 向ID为btnValidate的按钮添加一个onlclick事件处理程序
  • $("input[name='receptionattend']:checked").length returns how many input elements with a name of receptionattend are checked $("input[name='receptionattend']:checked").length返回$("input[name='receptionattend']:checked").length了多少个具有receptionattend名称的输入元素
  • the rest should be fairy self explanatory 其余的应该是童话自我解释

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

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