[英]How to check the radio button is selected or not
我正在研究测验系统。 在那我想做的是从数据库中收集问题,并使用php如下放置:
<div class="span12" style="margin-top:140px;">
<ul id="part">
<?php //print_r($quiz);
$i = 1;
foreach($quiz as $quiz)
{
echo "<li id='div$i' style='display:none;'>
<p style='font-size:20px;'><strong>Question $i </strong>: $quiz->Question </p>
<br/><div style='margin-left:60px;font-size:14px;'>
<input type='radio' name='op11' id='op1$i' value='1' style='opacity: 0;'>$quiz->op1<br/><br/>
<input type='radio' name='op11' id='op2$i' value='2' style='opacity: 0;'>$quiz->op2<br/><br/>
<input type='radio' name='op11' id='op3$i' value='3' style='opacity: 0;'>$quiz->op3<br/><br/>
<input type='radio' name='op11' id='op4$i' value='4' style='opacity: 0;'>$quiz->op4<br/><br/></div>
</li>";
$i++;
}
?>
</ul>
<div class="span6">
<button id="next" class="btn btn-info btn-large" style="float:right;">Next → </button>
</div>
</div>
现在使用jQuery,当我单击下一步按钮时,所选答案的值将放入名为答案的数组中。
当选择答案时,将创建更正数组,但是当我没有选择任何答案时,则将前一个值推入数组。
为此,我使用以下jquery函数:
<script>
$(function(){
var items = $('ul#part li');
var answers = new Array();
if(items.filter(':visible').length == 0)
{
items.first().show();
}
$('#next').click(function(e){
//e.preventDefault();
var active = items.filter(':visible:last');
active.hide();
var val = $("input:radio[name=op11]:checked").val();
console.log(val)
answers.push(val)
var next = active.next();
if (next.length)
next.show();
else{
console.log(answers);
}
});
});
</script>
例如:我有三个问题,分别选择答案2,3,1,那么答案数组是[2,3,1]是正确的,但假设我没有选择任何一个问题,答案不是两个,则选择第一个问题和第三个问题的答案分别是2,3,然后根据我的代码创建的数组是[2,2,3]。 但是我需要,当我不选择任何答案时,该答案的值应为0意味着在上面的示例中,数组应为[2,0,3]
我该如何实现,请帮助我更正代码
将id用于单选按钮:
例:
if(document.getElementById('op1$i').checked) {
//radio button is checked
您应该检查是否选择了当前答案。 尝试类似的方法:
if ($("input:radio[name=op11]:checked").length == 1) {
//One item checked with that name
var val = $("input:radio[name=op11]:checked").val();
} else { var val=0; } //or handle the error some other way
var val = $("input:radio[name=op11]:checked").val();
if (typeof(val) !== "undefined" && val !== null){
answers.push(val);
}else{
answers.push(0);
}
您需要检查它是否不是null或未定义。 如果为(空或未定义),则添加0,否则添加所选值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.