[英]I have to validate my form for radio buttons using javascript for my code given below
i have retrieve questions and answers from the sql table and represented them using this code. 我已经从sql表中检索了问题和答案,并使用此代码表示了它们。 now, i have a problem that how to take the radio button name in javascript. 现在,我有一个问题,如何在javascript中使用单选按钮名称。 for every question there must be a one option checked. 对于每个问题,必须选中一个选项。 i have to do this for all questions. 对于所有问题,我都必须这样做。
<form action="answer.php?title=<?php echo $_GET['title'];?>" method="post">
<table id="myques">
<?php
$i=0;
while($row=mysql_fetch_array($result)){
?>
<tr>
<td><?php echo ++$i.')'; ?></td>
<td>   <?php echo $row['question']; ?></td>
</tr>
<tr>
<td></td>
<td><input type="radio" name="<?php echo $row['question'];?>" id="ques" value="<?php echo $row['opt1'];?>"><?php echo $row['opt1']; ?></td>
</tr>
<tr>
<td></td>
<td><input type="radio" name="<?php echo $row['question'];?>" id="ques" value="<?php echo $row['opt2'];?>"><?php echo $row['opt2']; ?></td>
</tr>
<tr>
<td></td>
<td><input type="radio" name="<?php echo $row['question'];?>" id="ques" value="<?php echo $row['opt3'];?>"><?php echo $row['opt3']; ?></td>
</tr>
<tr>
<td></td>
<td><input type="radio" name="<?php echo $row['question'];?>" id="ques" value="<?php echo $row['opt4'];?>"><?php echo $row['opt4']; ?></td>
</tr>
<?php } ?>
<tr><td colspan="4"><input type="submit" name="add" onClick="return validate()" /></td></tr>
</table>
Try this: 尝试这个:
<input type="radio" name="question" id="ques" value="1">
<input type="radio" name="question2" id="ques2" value="2">
<input type="radio" name="question3" id="ques3" value="3">
Or you decide on names make sure they are different.. 或者您决定使用名称以确保它们不同。
And for JS: 对于JS:
var projectObj = document.form1.project
var len = projectObj.length
var chosen = null;
for (i = 0; i <len; i++) {
if (projectObj[i].checked) {
chosen = projectObj[i].value
}
}
if (chosen == null) {
alert("No Radio Button Chosen")
}
SOURCE CREDIT GIVEN TO : How to check if one of radio buttons was selected? 来源信用给 : 如何检查是否选择了单选按钮之一?
There is no easy way to do this. 没有简单的方法可以做到这一点。 Or you can use default checked option in your HTML. 或者,您可以在HTML中使用默认选中的选项。 I think it will be conflict with your business. 我认为这将与您的业务冲突。 In your JS: 在您的JS中:
// store your question names in JS array
// check them group by group. and it will give detail information for which question is not check.
OR In your JS: 或在您的JS中:
// I think there will be four option answers in one question.
// count the total number of questions. and make the radion id as "radion1","radion2"...
// for all radios, if the checked number is equals with the question, the form submit is valid.
<td><input type="radio" name="<?php echo $row['question'];?>" id="ques<?=$i?>" value="<?php echo $row['opt1'];?>" checked="true"><?php echo $row['opt1']; ?></td>
这就是您想要的吗?只需在第一个选项中添加checked =“ true”,然后您就可以做到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.