mandatory radio button checked in form not working

3.5k views Asked by At

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
2

There are 2 answers

0
Funk Forty Niner On BEST ANSWER

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.

2
Soufiane Hassou On

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.