简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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