0

I need help validating radio buttons with JavaScript. Here's the section of 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.

3
  • y is always going to have a value, either true or false, you should check for false :: if (!y) {} Commented Oct 3, 2013 at 2:47
  • Now it's not even giving me my error message. My issue before was I got the message even when I chose an option. :S Commented Oct 3, 2013 at 2:59
  • Oops! My apologies, I changed something else without realising. Still having the error message at all times issue. Commented Oct 3, 2013 at 3:03

3 Answers 3

2

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.

However, should you need to check for null or undefined, you should use typeof and strict comparison with ===

 (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? 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. If nothing was checked y_value will be null.

Sign up to request clarification or add additional context in comments.

4 Comments

I've tried using this, but I'm still getting a error message even when I have an option selected.
On a side note, I'll disagree with the blanket statement that you should check a radio button by default. There are times when you want the user to have to actualy think about what they are doing. Often a user will leave a radio button in the default state out of lazyness/ignorance/apathy. For example in a survey, you want the user to explicitly choose an answer.
Glad it worked for you Ashley! @Jon P - Radio button group represents a 1 of many selection like a single-select list or dropdown. Its best to always have exactly one radio button selected. Refer to [link]w3.org/TR/html401/interact/forms.html#radio If you need to make sure a user makes a choice, you could let the pre-selected choice be 'Not specified' analogous to an empty or a '--Select one--' first element in a drop-down. Not having a pre-selected choice is a bit weird, since you then have a state to which the user cannot go back. Once he has made a choice, he can't undo it.
I agree that most times you should set a default, but I disagree that you should always set a default. I'll set a default 90-95% of the time. I wouldn't for example present a radiobutton that wasn't a valid selection, your "Not Specified" for example, then via validation inform the user that it is not a valid selection. To me thats worse than not pre-selecting an option. I know I'm arging against the spec here and leave it at that as this isn't the forum for an extended debate.
1

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:

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

2 Comments

Ok, I'm still having an issue. It returns an error message even when I've selected an option.
@AshleyMarieRoberts check the added answer with demo
0

I'm not going to suggest using jquery just for this. But should you end up using jquery, it makes this kind of validation very easy.

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.

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

$("#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/

To break down the script

  • $("#btnValidate").click(function(){}); adds an onlclick event handler to the button with ID btnValidate
  • $("input[name='receptionattend']:checked").length returns how many input elements with a name of receptionattend are checked
  • the rest should be fairy self explanatory

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.