Anjan Baradwaj
Anjan Baradwaj

Reputation: 1229

Validating group of radio buttons

function validate()
{
      var a = document.getElementById("a");
      var b = document.getElementById("b");
      var valid = true;


 if(a.value.length<=0 || b.value.length<=0 || a.value.trim()=="" || b.value.trim()=="")
       {
              alert("Don't leave the field empty!");
              valid = false;
       }

   if(isNaN(a.value) || isNaN(b.value))
    {
            alert("Enter a proper number!");
            valid = false;
    }

   for(var i=0; i<form.elements.length; i++)
   {
       if(form.elements[i].checked)
       {
                 valid = true;
       }
       else
       {
           alert("No option selected!");
           valid = false;
       }
    }
         return valid;
 };

This is my JavaScript function to validate group of radio buttons to check if atleast one of them is selected. And, the one below is my form.

<form name="myForm" font-size="75px;" action ="serv" method="get" onsubmit="return validate();" >
        <hr/>
        Enter the 1st number: <input type="text" name="a" id="a" /><br/>
        Enter the 2st number: <input type="text" name="b" id="b"/><br/><br/>
        <label>Add</label><input type="radio" name="option" value="Add" id="r1" /><br/>
        <label>Subtract</label><input type="radio" name="option" value="Subtract" id="r2" /><br/>
        <label>Multiply</label><input type="radio" name="option" value="Multiply" id="r3" /><br/>
        <label>Divide</label><input type="radio" name="option" value="Divide" id="r4" /><br/>
        <input type="submit" value="Submit" />


</form>

When i give input and no radio button is selected it should alert the user, but its not happening. Can someone guide where I've gone wrong? And help me out with this? I know there might be lot of duplicates, but I've tried them all to no avail. When i click submit without selecting the radio button it gives me a blank page. Any help is appreciated. Thanks.

Upvotes: 0

Views: 1584

Answers (1)

Voonic
Voonic

Reputation: 4785

Try this, Check the demo here Fiddle

function validate()
{
      var a = document.getElementById("a");
      var b = document.getElementById("b");
      var valid = true;

      if(a.value.length<=0 || b.value.length<=0 || a.value.trim()=="" || b.value.trim()=="")
      {
              alert("Don't leave the field empty!");
              valid = false;
      }

      if(isNaN(a.value) || isNaN(b.value))
      {
            alert("Enter a proper number!");
            valid = false;
      }

      var ele = document.getElementsByName("option");
      var flag=0;
      for(var i=0; i<ele.length; i++)
      {
        if(ele[i].checked)
        {
           flag=1;
           break;
        }
      }
      if(flag == 0)
      { 
         alert("No option selected!");
         valid = false;
      }
      return valid;
 };

Upvotes: 2

Related Questions