[英]jQuery - Check if any specific radio buttons are checked
jQuery 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 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>
I want to check if any of the 'correctAnswers' checkboxes are checked. 我想检查是否选中了“ correctAnswers”复选框。
At the moment if I selected 'answer1d' it returns:- 目前,如果我选择“ answer1d”,它将返回:
alert('One of the radio buttons is checked!');
Any idea how I can loop through each answer and see if either are checked? 知道我如何遍历每个答案并查看是否已选中吗?
You could change correctAnswers
to an array of id
attributes, then use the .indexOf()
method to check if the checked element's id
is in the array: 您可以将
correctAnswers
更改为一个id
属性数组,然后使用.indexOf()
方法检查被检查元素的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!');
}
You can filter checked elements along with .length
to get checked elements count: 您可以将选中的元素与
.length
一起过滤,以获取选中的元素数:
var correctAnswers = ("#answer1d,#answer2c,#answer3c");
if(!$(correctAnswers).filter(':checked').length) {
alert('Nothing is checked!');
}
else {
alert('One of the radio buttons is checked!');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.