的jQuery
$('input').change(function() {
$('input:radio').prop('disabled', true);
$('.answer-detail').show();
$(this).next('label').addClass('correct');
var correctAnswers = ("#answer1d", "#answer2c", "#answer3c");
if (!$(correctAnswers).is(":checked")) {
alert('Nothing is checked!');
} else {
alert('One of the radio buttons is checked!');
}
});
HTML
<p>1: <span>What colour is the snowflake?</span></p>
<input class="answer" id="answer1a" type="radio" name="answer1" value="answer1a" /><label for="answer1a">Monochrome</label>
<input class="answer" id="answer1b" type="radio" name="answer1" value="answer1b" /><label for="answer1b">White</label>
<input class="answer" id="answer1c" type="radio" name="answer1" value="answer1c" /><label for="answer1c">Pantone 000C</label>
<input class="answer" id="answer1d" type="radio" name="answer1" value="answer1d" /><label for="answer1d">None of the above</label>
我想检查是否选中了任何'correctAnswers'复选框。
如果我选择'answer1d',它会返回: -
alert('One of the radio buttons is checked!');
知道如何循环查看每个答案,看看是否有人检查过吗?
答案 0 :(得分:2)
您可以将correctAnswers
更改为id
属性数组,然后使用.indexOf()
method检查已检查元素的id
是否在数组中:
var correctAnswers = ["answer1d", "answer2c", "answer3c"];
if (correctAnswers.indexOf(this.id) > -1) {
alert('One of the radio buttons is checked!');
} else {
alert('Nothing is checked!');
}
答案 1 :(得分:0)
您可以使用.length
过滤选中的元素以获取已检查的元素数:
var correctAnswers = ("#answer1d,#answer2c,#answer3c");
if(!$(correctAnswers).filter(':checked').length) {
alert('Nothing is checked!');
}
else {
alert('One of the radio buttons is checked!');
}