开发者

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:

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. 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:

<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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜