views:

78

answers:

2

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

+4  A: 

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.

Jeriko
LOL, +1 my answer (a few seconds later) was almost *identical*.
T.J. Crowder
@OP: The one thing my answer had that this doesn't: Why not just make one of the buttons pre-selected? Then you'll know that there's always one selected, no validation required...
T.J. Crowder
:D I need the rep, you definitely don't!
Jeriko
A: 

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.

Pointy
I totally never made that connection... I remember "tricking" the radio into breaking, was always fun :D Your post made me lol :)
Jeriko