jQuery:Looping all radio buttons inside an HTML table
Asked Answered
A

8

7

I have an HTML table having n rows and each rows contain one radiobutton in the Row.Using jQuery , How can i look thru these radio buttons to check which one is checked ?

Adios answered 17/5, 2010 at 19:19 Comment(0)
P
10
$('#table tbody tr input[type=radio]').each(function(){
 alert($(this).attr('checked'));
});

HTH.

Phocine answered 17/5, 2010 at 19:23 Comment(1)
#table > tr will choke on certain browsers (chrome/firefox) that like to add their own tbody elements, whereas #table tr won't.Fucoid
F
4

There are many ways to do that, e.g., using .each and the .is traversal method:

$("table tbody tr td input[name=something]:radio").each(function() {
    if($(this).is(":checked")) {
        $(this).closest("tr").css("border", "1px solid red");
    } else {
        // do something else
    }
});
Fucoid answered 17/5, 2010 at 19:25 Comment(2)
I'll give +1 if you can tell me if it is pretty well guaranteed that all (jQuery supported) browsers will reliably insert a missing <tbody>.Streptococcus
@patrick - No, that's not the case. Which means that my selector is broken some of the time. Which means I'll edit this answer now. Damn it, but thanks, I should pay more attention to my own answers in the future :)Fucoid
P
4

To loop through all the radio checked radio buttons, you can also do this:

$('input:radio:checked').each(function() {
    //this loops through all checked radio buttons
    //you can use the radio button using $(this)
});
Probation answered 17/8, 2012 at 20:54 Comment(0)
A
3
$('.my-radio-class:checked')

http://api.jquery.com/checked-selector/

Allowable answered 17/5, 2010 at 19:23 Comment(0)
H
3

Do you want to process every radio button or do you only need the checked ones? If the latter, it is quite easy:

$('table input:radio:checked')

Reference: :radio, :checked

Hygro answered 17/5, 2010 at 19:24 Comment(1)
+1. Afaik jQuery's look-up goes from right to left, so the whole thead tr td is unnecessary if the only condition is that they need to be in a table. And :radio and :checked are the most ‘elegant’ selectors in this case.Loewe
J
1
var checked = $('#table :radio:checked');
Jewett answered 17/5, 2010 at 19:25 Comment(0)
K
0
$("table tr input[type=radio]:checked");
Kilah answered 17/5, 2010 at 19:24 Comment(0)
M
0
//get the checked radio input, put more specificity in the selector if needed
var $checkedRadio = $("input[type=radio]:checked");

//if you want the value of the checked radio...
var checkedRadioVal = $checkedRadio.val();
Mark answered 17/5, 2010 at 19:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.