How to loop through a radio buttons group without a form?
Asked Answered
V

3

23

How do I loop through a radio buttons group without a form in JavaScript or jQuery?

Verlinevermeer answered 13/8, 2010 at 0:45 Comment(0)
W
30

What about something like this? (using jQuery):

$('input:radio').each(function() {
  if($(this).is(':checked')) {
    // You have a checked radio button here...
  } 
  else {
    // Or an unchecked one here...
  }
});

You can also loop through all the checked radio buttons like this, if you prefer:

$('input:radio:checked').each(function() {
   // Iterate through all checked radio buttons
});
Weatherspoon answered 13/8, 2010 at 0:48 Comment(0)
N
12

...in case someone wants to do this without jQuery (since it was part of the question):

I'm not sure what you mean by without a form. If you mean you don't want to pass the form element to a javascript function, you could do it like this:

for (var i = 0; i < document.form_name.radio_name.length; i++) {
    if (document.form_name.radio_name[i].checked) {
        // ...
    }
}

If you mean without a form as in you have no form node, you could wrap them in a span (or a div) and use code like this:

var span = document.getElementById("span_id");
var inputs = span.getElementsByTagName("input");
for (var i = 0; i < inputs.length; ++i) {
    if (inputs[i].checked) {
        // ...
    }
}
Notify answered 5/8, 2011 at 22:36 Comment(0)
D
3

I can't be too sure what you mean but if you want to do something to all radio buttons on a page you can do this:

$("input:radio").each(function(){
   //do something here
});
Dibri answered 13/8, 2010 at 0:47 Comment(4)
The selector "radio" will return nothing. There's no element (tag) called "radio" in HTML. It's <input type="radio">Westberg
$(':radio') is equivalent to $('[type=radio]'). api.jquery.com/radio-selectorClear
@Dumb Guy: I think @Westberg was referring to a previous edit, which was fixed by @Razor StormWeatherspoon
@Daniel & Dumb Guy, yeah I made a mistake earlier and corrected it after realizing.Dibri

© 2022 - 2024 — McMap. All rights reserved.