tags:

views:

246

answers:

2

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();
+5  A: 

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();
}
Doug Neiner
Couldn't you narrow the first two lines down to just `if ($("input[name='html_elements']:checked").length == 0){` ?
R. Bemrose
You could, but then you would need another full jQuery selection to get the value if you showed a value existed.
Doug Neiner
+1  A: 
if (!$("input[name='html_elements']:checked").val()) {
   alert('Nothing is checked!');
}
else {
  alert('One of the radio buttons is checked!');
}
Dominic Rodger
This will fail if the checked radio button has a value=""
ScottE
@ScottE - excellent point - I'll remove this answer if Roland unaccepts it.
Dominic Rodger
I think you could just change it to `.val() == ""` and remove the `!` and you would be all set.
Doug Neiner
@Doug - wouldn't that still have the problem ScottE mentioned? What would `.val()` return if the checked radio button had `value=""`? (Though I suppose you could argue that's a fairly unlikely case).
Dominic Rodger
Sorry, my comment was confusing: I meant for the whole test to look like this: `if ($("input[name='html_elements']:checked").val() == "")` Which would alert "Nothing is checked"
Doug Neiner