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:

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

Solution 3:

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

<script type="text/javascript">
function checkForm(formname)
{
if(formname.radiobuttonname.value == '') {
alert("Error: Please select a radio button!");
return false;
}
document.getElementById('submit').value='Please wait..';void(0);
return true;
}
</script>

<form name="formname" onsubmit="return checkForm(this)"

<input type="radio" value="radio1" name="radiobuttonname" style="display:inline;"> Radio 1<br>
<input type="radio" value="radio2" name="radiobuttonname" style="display:inline;"> Radio 2<br>

<input type="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:

<form name="form1">
  <input type="radio" name="foo"> Foo1<br/>
  <input type="radio" name="foo"> Foo2<br/>
</form>
<script type="text/javascript">
  var oneFooIsSelected = function() {
    var radios = document.form1.foo, i;
    for (i=0; i<radios.length; i++) {
      if (radios[i].checked) {
        return true;
      }
    return false;
  };
</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"