5

How can I determine if my radio buttons are selected?

For example:

if ( radio_button_selected ) { // do something } else { // do something else } 
1
  • This question has been asked before numerous times. Please search for the answer before asking the question. stackoverflow.com/questions/4138300/… Commented Nov 9, 2010 at 22:25

4 Answers 4

7

You can use this selector to determine if any are checked:

jQuery("input[name='my_button_group']:checked") 

So for example:

if (jQuery("input[name='my_button_group']:checked")) { ... } else { ... } 
Sign up to request clarification or add additional context in comments.

5 Comments

why do I need .length > 0 ?
@StaceyH - you don't in JavaScript, but this is a much faster selector than the other answer (because of the input).
@Nick Craver ...wasnt sure if you can see my comments from my post..but take a look
@John - I suppose you might need that check, but it would also be pretty poor naming if a checkbox had the same name as a radio, since the value would always screw up the form serialization output :)
@Nick.. Agreed but I have seen the situation where a checkbox and a radio had the same name but one was disabled and the other enabled. This changed due to other elements on the form. This question just really made me think about that scenario.
1

If you have your radio button rb already selected through other means, you can do:

var rb = $('whatever selector'); // other code if (rb.is(':checked')) { // code } 

6 Comments

+1 for being able to re-use rb for something else in the code (like getting val())
@jelbourn rb.checked is a better choice - it's faster and more readable.
@Šime Vidas: checked is not a property of a jquery list object. The actual DOM object has the checked property.
@jelbourn Yes, my mistake. rb[0].checked is the correct solution (and it is still faster).
@Šime Vidas: You're definitely right about it being faster; I did a little experiment and found it to be roughly 22 times faster.
|
1

If you have a reference to the element already, you can use its checked property:

$('input[type=radio]').focus(function(){ // "this" is the element that was clicked if (this.checked) { // do something } else { // do something else } }); 

2 Comments

Isn't that pointless since if the user "clicked" a radio button, it will always be "checked", hence you'll NEVER get to the ELSE condition of your code above
@StaceyH A very good point. Changed to focus to illustrate my point.
0
if ($("input[name='yourRadioName']:radio:checked").length) { } else { } 

1 Comment

@Nick Craver... There is a difference in Justin's method vs. mine. the :radio ensures that a radio button is selected and not just any checked input with the name "yourRadioName".. However you are right using input would execute faster.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.