Reputation: 165
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) {
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?
Upvotes: 1
Views: 40
Reputation: 524
I found these examples from the internet..
<script type = "text/javascript">
function Validate()
{
var RB1 = document.getElementById("<%=RadioButtonList1.ClientID%>");
var radio = RB1.getElementsByTagName("input");
var isChecked=false;
for (var i=0;i<radio.length;i++)
{
if (radio[i].checked)
{
isChecked=true;
break;
}
}
if(!isChecked)
{
alert("Please select an item");
}
return isChecked;
}
</script>
More reference on validate-aspnet-radiobuttonlist, ASP.Net-RadioButtonList-Control.aspx
Upvotes: 0
Reputation: 29036
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
}
Upvotes: 1