1

I have two radio buttons, yes and no.

I want to check if any of the radio buttons are checked and if not, then default the no radio button to checked.

Here is my attempt:

if ($("#type_No").attr('checked', false) && $("#type_Yes").attr('checked', false)) {
    $('#type_No').attr('checked', true);
}

However, while testing this, I realized this is incorrect because it's setting the values of the checkboxes and not checking if they're checked or not.

So, how do I check if a radio button is checked or not based on the id of the radio button?

Paweł Tomkiel
  • 1,974
  • 2
  • 21
  • 39
Kala J
  • 2,040
  • 4
  • 45
  • 85

2 Answers2

2

You can use $.is with selector :checked, like so

if (!$("#type_No").is(':checked') && !$("#type_Yes").is(':checked')) {
    // do something
}

Example

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
1

I assume your radio buttons have a name property, so simply do:

var isChecked = $("[name='RADIONAMEHERE']:checked").length > 0
tymeJV
  • 103,943
  • 14
  • 161
  • 157