-3

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
Jonas
  • 121,568
  • 97
  • 310
  • 388
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • What is the value of instrument when no button is selected? – demize May 30 '12 at 02:15
  • @demize there isn't a default value. One of the radio buttons "must" be clicked in order for the form to continue. – Funk Forty Niner May 30 '12 at 02:21
  • I know there's no default value, I meant when no button is selected what would be the output of something like `echo instrument` (I don't know much about Javascript, so I can't really test it myself, I would if I could because I'm interested in why this doesn't work.) Maybe you need to use `null` or something similar instead of a null string? – demize May 30 '12 at 20:23

2 Answers2

1

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.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
0

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.

Soufiane Hassou
  • 17,257
  • 2
  • 39
  • 75
  • That would work, but it's normally better to make sure that the user input what they wanted than the random value that was preselected. – demize May 30 '12 at 00:19
  • @Soufiane Hassou The radio button in the form must be selected. I don't want the form to be executed if a radio button is not clicked. – Funk Forty Niner May 30 '12 at 00:20