Using JQuery to check if no radio button in a group has been checked

Viewed 138222

I'm sitting with a problem, I need to check with JQuery if no radio button within a radio button group has been checked, so that I can give the users an javascript error if they forgot to check a option.

I'm using the following code to get the values

var radio_button_val = $("input[name='html_elements']:checked").val();
8 Answers
if (!$("input[name='html_elements']:checked").val()) {
   alert('Nothing is checked!');
}
else {
  alert('One of the radio buttons is checked!');
}

You could do something like this:

var radio_buttons = $("input[name='html_elements']");
if( radio_buttons.filter(':checked').length == 0){
  // None checked
} else {
  // If you need to use the result you can do so without
  // another (costly) jQuery selector call:
  var val = radio_buttons.val();
}
Related