Funk Forty Niner
Funk Forty Niner

Reputation: 74216

mandatory radio button checked in form not working

I have been at this for well over an hour and searched here and on the Web for an answer, but can't get this to work, so I am now asking for some help please.

I have a form where all fields are mandatory to be filled, including a "Radio" button to be selected, the radio button group called "instrument".

Any help is appreciated.

Here is my Javascript:

<script type="text/javascript">

    function checkFields(f) {
        name1 = document.form1.name1.value;
        name2 = document.form1.name2.value;
        email1 = document.form1.email1.value;
        instrument = document.form1.instrument.value;
        stylemusic = document.form1.stylemusic.value;

        if ((name1 == "") || (name2 == "") || (email1 == "") || (instrument == "") || (stylemusic == "")) {
            alert("All fields need to be filled.");
            return false;
        }
}

and my form code:

<input type="radio" value="percussion" name="instrument">Percussion
<input type="radio" value="wind" name="instrument">Wind

Upvotes: -3

Views: 3581

Answers (2)

Funk Forty Niner
Funk Forty Niner

Reputation: 74216

I found my answer and am posting it here, in case someone is faced with the same problem:

if((document.form1.instrument[0].checked==false)&&(document.form1.instrument[1].checked==false))

{
alert('You must make a choice');
return false
}

Note: Add another instance of [2], [3] etc in order to accomodate for more radio button choices.

Upvotes: 1

Soufiane Hassou
Soufiane Hassou

Reputation: 17750

You don't need to use validation against radio buttons, just make one of your radio buttons checked by default, this way, you'll be sure that every group has a checked button.

This accomplishes two things:

  • Required groups are checked
  • No need to javascript validation

Of course, I'm assuming that you are using groups, radio buttons don't make sense individually, they need to be grouped.

Upvotes: 0

Related Questions