esoteric
esoteric

Reputation: 125

JQuery - ASP.NET - Get the value of radio buttons and tally

I need to recreate a simple JS page that is taking radio button values for yes and no questions and displaying the results of what was selected, Unfortunately ASP.NET is blocking the way... Anyone know how to get around the problem of net being able to get the values correctly in .NET, with no back end?

<script type="text/javascript" language="javascript">
function scoreQuiz(form) {

    var count = 0;

    if ($('#<%=rbYesOne.ClientID%> radio:selected').val() == "1") {
        alert("YES");
    }

    if ($('#<%=rbNoOne.ClientID%> radio:selected').val() == "0") {
        alert("NO");
    } 

    else {
        alert("FU......");           
    }
</script>

<div class="row">
    <asp:RadioButton ID="rbYesOne" value="1" runat="server" GroupName="Question1" />
    <asp:RadioButton ID="rbNoOne" value="0" runat="server" GroupName="Question1" />
     <!-- and twelve more... -->
</div>


<script type="text/javascript" language="javascript">
    var rbYesOne = document.getElementById('<%=rbYesOne.ClientID%>');
    var rbNoOne = document.getElementById('<%=rbNoOne.ClientID%>');
    /* and twelve more...*/
</script>

Upvotes: 1

Views: 4636

Answers (2)

Bibhu
Bibhu

Reputation: 4081

You can use :

$("#<%=rbYesOne.ClientID%>").change(function() {
    alert("YES");
});

$("#<%=rbNoOne.ClientID%>").change(function() {
    alert("NO");
});

Upvotes: 0

Adam Rackis
Adam Rackis

Reputation: 83358

To check if a radio button is checked, select it with the :checked filter, then see if any results were found with the length property:

if ($('#<%=rbYesOne.ClientID%>:checked').length === 0) {
    alert("NO");
} 

Or use the is function:

if ($('#<%=rbYesOne.ClientID%>').is(":checked")) {
    alert("NO");
} 

Also, working around asp.net auto-generated IDs can be a pain. To make life easier you can give the radio buttons unique class names, and then do simply:

if ($('.rbOne:checked').length === 0) {
   alert("NO");
} 

Upvotes: 2

Related Questions