March 19, 2012

how to check if there is one selected radio button among the group?

Question by assehj

Good day… I am here again to ask your idea on solving this problem. I have displayed questions using while loop. Each questions have 5 radio buttons each. The problem is, I have to check if one among the group of radio button is clicked. How to do this one using php or javascript? I have here my sample program.. Thanks in advance…

$ctr = 1;
$partIDTemp = "";
while($rowItems = mysql_fetch_array($resultItems)){                          
   if( $partIDTemp != $rowItems['partID'] ){
      if($ctr != 1)
         echo "<tr ></tr>";
         echo "<tr style='font-family: Arial, Helvetica, sans-serif; font-weight:bold'><td colspan='3'>" . $rowItems['description'] . "</td></tr>";
echo "<tr bgcolor=white style='font-family: Arial, Helvetica, sans-serif;'><td align='center'>" . $ctr . "</td>";
$rows =$rowItems['WPID'];
echo "<td>" . $rowItems['descriptions']. "</td>";
$response = "response_".$rows;
echo "<td><input type='radio' name='$response' value='5' />
      <input type='radio' name='$response' value='4' />
      <input type='radio' name='$response' value='3' />
      <input type='radio' name='$response' value='2' />
      <input type='radio' name='$response' value='1' />
$partIDTemp = $rowItems['partID'];

Answer by Starx

Since you are monitoring the users activity, you have you use Javascript, unless you can wait till the form is submitted.

Using jQuery, you can attach a snippet on the submit event like this

$("#formid").submit(function() {
   var checked = $(this).children('input[name="checkboxname"]:checked').val();


Pure javascript of this would be this

var myform = document.forms['myform'];
myform.onsubmit = function() {
   var elements = myform.getElementsByTagName("input");
   var value;
   for(var i =0; i< elements.length; i++) {
      if(elements[i].type == "radio" && elements[i].checked) {
         value = elements[i].value;
   return false;

Here is a demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!