简体   繁体   English

单选按钮的Java验证

[英]Javascript validation for radio button

I am doing newsletter subscription.I have 2radio buttons-subscribe and unsubscibe and a submit button.But when I click on submit button,ajax function gets called for subscription.Now i want to do validation.I have written a javascript validation for radio buttons as below: 我正在做新闻订阅。我有2个单选按钮-subscribe和unsubscibe,还有一个Submit按钮。但是当我单击Submit按钮时,ajax函数被要求订阅。现在我要进行验证。我为单选按钮编写了javascript验证如下:

function validate_radio()
              {
                    var radio_choice = false;
                    var radio_val = document.newsletterform.subscribe.length;
                    for (counter = 0; counter < radio_val; counter++)
                    {
                        if (document.newsletterform.subscribe[counter].checked)
                        radio_choice = true; 
                    }
                    if (!radio_choice)
                    {
                        document.getElementById("mandatory").innerHTML="Select Subscribe/Unsubscribe";
                        return false;
                    }

               }

But now I am getting the validate message but at the same time i am getting subscribed. 但是现在我收到验证消息,但与此同时我得到了订阅。 tell me a way so that i can stop the subscription being done if the function returns false. 告诉我一种方法,以便如果函数返回false,我可以停止完成订阅。 I am calling the function as follows: 我正在调用该函数,如下所示:

Sounds like your form isn't stopping when it should be. 听起来您的表单并没有停止。 I assume you have something like 我想你有类似的东西

 <form onsubmit="validate_radio()">...</form>

Since your validate_radio() function returns false on failure, you just need to modify your form to fail if the validation does: 由于您的validate_radio()函数在失败时返回false,因此如果验证确实需要,则只需将表单修改为失败即可:

<form onsubmit="return validate_radio()">...</form>

So the form will halt if validation fails. 因此,如果验证失败,表单将暂停。

For what it's worth, I think that it's not good for a form to include radio buttons that don't start off with one being selected. 对于它的价值,我认为表单包含没有以选择一个按钮开始的单选按钮是不好的。 Young people don't remember old radios, or being yelled at for messing around with the buttons to get them all to pop out. 年轻人不记得以前的收音机,也不会因为把按钮弄得一团糟而被大吼大叫。 Radio buttons are called "radio buttons" because one of them must always be selected . 单选按钮称为“单选按钮”,因为必须始终选择其中一个 It's friendlier for your users to have the buttons initialized to a good default setting. 将按钮初始化为良好的默认设置对您的用户来说更为友好。

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

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