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' />
</td>";
$ctr++;
$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;
break;
}
}
alert(value);
return false;
}
Here is a demo