简体   繁体   中英

jQuery - Check if any specific radio buttons are checked

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> 

I want to check if any of the 'correctAnswers' checkboxes are checked.

At the moment if I selected 'answer1d' it returns:-

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:

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

You can filter checked elements along with .length to get checked elements count:

var correctAnswers = ("#answer1d,#answer2c,#answer3c");
if(!$(correctAnswers).filter(':checked').length) {
   alert('Nothing is checked!');
}
else {
  alert('One of the radio buttons is checked!');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM