samantha07
samantha07

Reputation: 507

Check if all radio buttons are true

I have 8(4 yes + 4 no) radio buttons and the last pair of button is 'All of the above (Yes/No)'. How do I check if all of the radio (1-3) YES are checked so I can set the last button to YES?

  1. YES NO Exam A
  2. YES NO Exam B
  3. YES NO Exam C
  4. YES NO All of the above

Here's my poor attempt (working) but I know its poorly written

//EXAMS
<input type="radio" class="yes-radio" name=""> YES
<input type="radio" class="no-radio" name=""> NO
..
..

//ALL OF THE ABOVE
<input type="radio" class="yes-radio-all" name=""> YES
<input type="radio" class="no-radio-all" name=""> NO


//inside click event
        var totalyes = $('.yes-radio').length;
        var totalno = $('.yes-radio').length;
        var yes = $('.yes-radio:checked').length;
        var no = $('.no-radio:checked').length;

        if (totalyes == yes) {
            $('.yes-radio-all').attr('checked', true);
        }

        if (totalno == no) {
            $('.no-radio-all').attr('checked', true);
        }

I simplified and not the actual code but you'll get what I mean. I think there must be some sort of loop or foreach that will solve my problem.

Thanks!

Upvotes: 0

Views: 113

Answers (2)

Charlie Bamford
Charlie Bamford

Reputation: 1309

You shouldn't need to do a loop. It's not a big deal in this case, but it's more generally more efficient to rely on browser built-ins rather than rolling a custom implementation for things.

Also, simple loops have a time complexity of O(n) by definition, where (depending on the implementation of course) css selectors have a complexity of O(1). Again, given that you are only iterating over a few things, it's not a big deal here.

You could also cut down the number of selectors by checking whether there are any checkboxes unchecked rather than counting all the checkboxes and then all the checked checkboxes:

// Check if all yes-radios are checked.
const allYes = !$('.yes-radio:not(:checked)').length;
$('.yes-radio-all').prop('checked', allYes);

// Check if all no-radios are checked.
const allNo = !$('.no-radio:not(:checked)').length;
$('.no-radio-all').prop('checked', allNo);

Upvotes: 1

Barmar
Barmar

Reputation: 781848

You can convert a jQuery selection to an array, and then use the standard every() method.

if ($('.yes-buttons').get().every(button => button.checked)) {
  $('.yes-radio-all').prop('checked', true);
} else if ($('.no-buttons').get().every(button => button.checked)) {
  $('.no-radio-all').prop('checked', true);
}

Upvotes: 1

Related Questions