Search code examples
htmlvalidationradio-button

Validate a Radio Button


I want to make a simple validation form, which will show warning message, when it will be uncheck in a <div>.

This is what, i come up till now.

<form action="result.php" method="post">
<b>1st question:</b><br />
Option 1 <input type="radio" name="question1" value="Option1" /><br />
Option 2 <input type="radio" name="question1" value="Option2" /><br />
Option 3 <input type="radio" name="question1" value="Option3" /><br />
Option 4 <input type="radio" name="question1" value="Option4" /><br />
<br />
<b>2nd question:</b><br />
Option 1 <input type="radio" name="question2" value="Option1" /><br />
Option 2 <input type="radio" name="question2" value="Option2" /><br />
Option 3 <input type="radio" name="question2" value="Option3" /><br />
Option 4 <input type="radio" name="question2" value="Option4" /><br />
<br />
<input type="submit" value="submit" />
</form>`

Solution

  • you can do this by jQuery. The length attribute it calculate The number of elements in the jQuery object

    $("#forms").submit(function(){ //or you can use click event 
       if ($("input[name='question1']:checked").length > 0){
      $('.show_message').html(' ');
      $('.show_message').html('selected  ');
    }
    else{
       $('.show_message').html(' ');
       $('.show_message').html(' no  one selected ');
       return false;
    }
    
    });
    

    and

    <div class="show_message"></div>
    <form id="form" action="result.php" method="post">
     . . . .
    </form>
    

    jsFiddle