jQuery - 检查是否选中了任何特定的单选按钮

时间:2015-12-14 14:56:58

标签: javascript 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

<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!');

知道如何循环查看每个答案,看看是否有人检查过吗?

2 个答案:

答案 0 :(得分:2)

您可以将correctAnswers更改为id属性数组,然后使用.indexOf() method检查已检查元素的id是否在数组中:

Updated Example

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!');
}