Steven Zack Steven Zack - 5 months ago 41
jQuery Question

How to loop through a radio button list

I searched online and didn't find a good method to select radiobuttonlist control in .net
So I add a class to each radiobuttonlist and using class selector to loop each, however, it seems that whenever one changes, all change. See my code as follows:
This is jQuery part:

function Checkform() {
result=true;
$('.rbl').each(function() {
var cc = $(this + "[checked]").val();
if (cc == undefined) {
result = false;
return false;
}
});
return result;
}


This is web part:

<form id="form1" runat="server" onsubmit="return Checkform();">
<asp:RadioButtonList ID="RadioButtonList1" class="rbl" runat="server">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:RadioButtonList>

<asp:RadioButtonList ID="RadioButtonList2" class="rbl" runat="server"
RepeatDirection="Horizontal">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
</asp:RadioButtonList>




What I want to do is to check if all radiobuttonlist control has its selected value before submitting the form. But it works like as one has selected value, the function will return true no matter weather the other one has selected value. Please help me on this issue. Thank you in advance.

Answer

How about this:

function Checkform() {
    var result = true;
    $('.rbl').each(function() {
        var checked = $(this).find('input:radio:checked');
        if (checked.length == 0) {
            result = false;
            return;
        }
    });
    return result;
}

This will examine each group and determine if there is a radiobuttom selected within that group. The key is $(this).find('..') which returns all the "checked" radio buttons within the current group which is zero if none are selected, and 1 if one is selected.