Skip to content Skip to sidebar Skip to footer

Radio Button Required - Javascript Validation

I know nothing of JavaScript. I had to add a group of two radio buttons to an HTML form with values 'yes' and 'no'. Now I need to make them 'required' There are several other requi

Solution 1:

Why don't you just make one selected by default then one will always be selected.

Solution 2:

A link to your page or a sample of your HTML would make this easier, but I'm going to hazard a guess and say that the values in the array match the "name" attribute of your radio button elements.

If this the case, "acknowledge" should be the name of both radio buttons, and to make things easier, one should have the attribute "checked" set to "true" so there is a default, so you'll get a value either way.

So, something like this:

<inputtype="radio" name="acknowledge" value="yes" /> Yes <br/>
<inputtype="radio" name="acknowledge" value="no" checked="true" /> No <br/>

Solution 3:

I know question is ancient but this is a simple solution that works.

<scripttype="text/javascript">functioncheckForm(formname)
{
if(formname.radiobuttonname.value == '') {
alert("Error: Please select a radio button!");
returnfalse;
}
document.getElementById('submit').value='Please wait..';void(0);
returntrue;
}
</script><formname="formname"onsubmit="return checkForm(this)"

<inputtype="radio"value="radio1"name="radiobuttonname"style="display:inline;"> Radio 1<br><inputtype="radio"value="radio2"name="radiobuttonname"style="display:inline;"> Radio 2<br><inputtype="submit"value="Submit"></form>

Solution 4:

Without seeing your HTML and more context of your validate function it's unclear exactly what you're looking for, but here's an example of how to require a selected value from a radio group:

<formname="form1"><inputtype="radio"name="foo"> Foo1<br/><inputtype="radio"name="foo"> Foo2<br/></form><scripttype="text/javascript">var oneFooIsSelected = function() {
    var radios = document.form1.foo, i;
    for (i=0; i<radios.length; i++) {
      if (radios[i].checked) {
        returntrue;
      }
    returnfalse;
  };
</script>

Here is a working example on jsFiddle.

Solution 5:

I always recommend using jQuery validate seems better to me than trying to re-invent the wheel

Post a Comment for "Radio Button Required - Javascript Validation"