user6234613 user6234613 - 5 months ago 15
jQuery Question

jQuery not validating RadioButtonList properly?

I want to use jQuery to validate

RadioButtonList
to ensure that user has checked on one of the values. If the user doesn't check on any of the radio buttons, an alert appears. However, the problem is that even after the user has checked on one of the radio buttons, the alert still prompts. The following jQuery codes I have seemed to be correct according to what I found online.

This is my
RadioButtonList
:

<asp:RadioButtonList ID="rbClass" runat="server" CssClass="rbClass">
<asp:ListItem Text="Asset Management Tool" Value="Asset Management Tool"></asp:ListItem>
<asp:ListItem Text="Backup Tool" Value="Backup Tool"></asp:ListItem>
<asp:ListItem Text="Communication Tool" Value="Communication Tool"></asp:ListItem>
<asp:ListItem Text="Developer Tool" Value="Developer Tool"></asp:ListItem>
</asp:RadioButtonList>


And this is my jQuery:

if ($('#rbClass').is(':checked') == false) {
//if ($('#rbClass').is(':not(:checked)')) {
//if (!($('#rbClass').is(':checked'))) {
//if ($('#rbClass radio[checked=false]')) {
//if (!$("#rbClass:checked").val()) {
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
alert("Please select the software's classification.");
}


As you can see, I've tried a few different ways of checking if the
RadioButtonList
has been checked. I've also tried using the
CssClass
attribute (
.rbClass
) to validate, and it doesn't work as expected either. Am I missing something?

Answer

You cannot access the ASP controls directly through javascript, since those controls will rendered as HTML so its Id will be changed and it will be related to the parent. So what you can do here is, Use its Client ID like the following:

var selectedCount=$("#<%=rbClass.ClientID %> input:checked").length;
if(selectedCount==0)
{
    // Statements here nothing is checked
}