What is the best way to add or remove a CSS class when a user selects a Radiobutton using JQuery?

Here is the ASPX markup I am working with. Users can select an answer by choosing a radiobutton labeled as the "winning question."

I have HiddenFields that contain either True or False.

If a user selects 'rdAnsBool1' and the 'HiddenField1' value is "True," JQuery should add a "correct" CSS class to the parent div with ID = Answer.

If the user selects 'rdAnsBool1' but the value of 'HiddenField1' is "False," then jQuery must add a "wrong" CSS class to the parent div with ID = Answer.

<div id="Answer" class="Ans">
   <div id ="Left"> 
   <asp:RadioButton ID="rdAnsBool1" runat="server" Text = '<%# DataBinder.Eval(Container.DataItem, "Ans1") %>' />
   <asp:RadioButton ID="rdAnsBool2" runat="server" Text = '<%# DataBinder.Eval(Container.DataItem, "Ans2") %>' />
   <asp:HiddenField ID="HiddenField1" runat="server" Value = '<%# DataBinder.Eval(Container.DataItem, "Ans1Bool") %>'/>
    </div>
</div>

I need help implementing this with JQuery.

Update: The Answer div is inside a Listview which is why I want to style the parent div.

Another Update: I'm nervous about using JQuery...

The markup has been modified as follows...hence the 200 bounty for the solution.

<div id="Answer" class="Ans">
           <div id ="Left"> 
           <asp:RadioButton ID="rdAnsBool1" runat="server" Text = '<%# DataBinder.Eval(Container.DataItem, "Ans1") %>' />
           <asp:RadioButton ID="rdAnsBool2" runat="server" Text = '<%# DataBinder.Eval(Container.DataItem, "Ans2") %>' />
           <asp:RadioButton ID="rdAnsBool3" runat="server" Text = '<%# DataBinder.Eval(Container.DataItem, "Ans3") %>' />
           <asp:RadioButton ID="rdAnsBool4" runat="server" Text = '<%# DataBinder.Eval(Container.DataItem, "Ans4") %>' />
           <asp:RadioButton ID="rdAnsBool5" runat="server" Text = '<%# DataBinder.Eval(Container.DataItem, "Ans5") %>' />
           <asp:RadioButton ID="rdAnsBool6" runat="server" Text = '<%# DataBinder.Eval(Container.DataItem, "Ans6") %>' />
           <asp:HiddenField ID="HiddenField1" runat="server" Value = '<%# DataBinder.Eval(Container.DataItem, "Ans1Bool") %>'/>
           <asp:HiddenField ID="HiddenField2" runat="server" Value = '<%# DataBinder.Eval(Container.DataItem, "Ans2Bool") %>'/>
           <asp:HiddenField ID="HiddenField3" runat="server" Value = '<%# DataBinder.Eval(Container.DataItem, "Ans3Bool") %>'/>
           <asp:HiddenField ID="HiddenField4" runat="server" Value = '<%# DataBinder.Eval(Container.DataItem, "Ans4Bool") %>'/>
           <asp:HiddenField ID="HiddenField5" runat="server" Value = '<%# DataBinder.Eval(Container.DataItem, "Ans5Bool") %>'/>
           <asp:HiddenField ID="HiddenField6" runat="server" Value = '<%# DataBinder.Eval(Container.DataItem, "Ans6Bool") %>'/>
           </div>
        </div>

Check out the JsFiddle link below for further details.

http://jsfiddle.net/VTevz/

This situation is really getting on my nerves!

Answer №1

// Grabbing a reference to the radio button and attaching a change handler
$('input[id*="rdAnsBool"]').change(function(){
     var container = $(this).closest('div.Ans'),
         questionid = $(this).attr('id'),
         index = questionid[questionid.indexOf('rdAnsBool') + 1];

     // Checking for condition and applying classes based on result ...
     if($(this).val() == $(this).parent()
                                .find('input[id*="HiddenField' + index + '"]').val()) {
          container.addClass('correct').removeClass('wrong');
          return;
     }

     container.addClass('wrong').removeClass('correct');
});

Update (Be sure to include HTML markup rather than ASP markup when working in the browser context):

http://jsfiddle.net/VTevz/7/

Answer №2

$('#rdAnsBool1').on('click', function(e) {
    if ($('#HiddenField1').val() === 'True') {
        $('#Answer').addClass('correct');
    } else {
        $('#Answer').addClass('wrong');
    }
});

Answer №3

By not grouping the radio buttons, it allows for both of them to be selected simultaneously. To prevent this, ensure that both buttons have the same GroupName.

Once you have designated a name, such as "answers," you can implement the following:

$('input[name="answers"]').click(function(){
    if($('#HiddenField' + $(this).index()).val().toLowerCase() == "true"){
        $("#Answer").removeClass('wrong').addClass('correct');  
    }
    else{
        $("#Answer").removeClass('correct').addClass('wrong');
    }
});

Answer №4

Ensure that the hidden field shares the same name as the radio button and follow these steps:

$('input[type=radio]').change(function() {
    if (this.checked == $('input[type=hidden],[name=' + this.name + ']').val()) {
        $(this).closet('#Answer').removeClass('correct').addClass('wrong');
    }
    else {
        $(this).closet('#Answer').removeClass('wrong').addClass('correct');
    }
});

Answer №5

To simplify the process, consider including the hidden field's ClientID as a value in your radio buttons. This can be achieved in the code-behind section (for example, during the radio button's pre-render event:

RadioButton1.Attributes.Add("value", HiddenField1.ClientID)
). Additionally, it might be beneficial to assign a CSSClass to the designated choice buttons (CSSClass="choice" or
RadioButton1.Attributes.Add("class", "choice")
depending on your preference for markup or code-behind implementation).

These adjustments will alter the resulting markup to something like

<input type="radio" value="ctl00_cphMain_HiddenField1" name="ctl00$cphMain$RadioButton1" id="ctl00_cphMain_RadioButton1">
.

After updating the markup, the corresponding jQuery script would be:

$('input.choice[type="radio"]').click(function () {
    var $this = $(this);         //alias for convenience.
    var answer = $this.val();   //id of hidden field
    var cssClass = '';
    if ($this.attr('checked')) {
        cssClass = $(answer).val().toLowerCase() === 'true' ? 'correct' : 'wrong';
    }
    $this.removeClass('correct').removeClass('wrong').addClass(cssClass);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The onblur and onfocus events in jQuery may experience some functionality issues when used in the IE browser

Utilizing the onblur and onfocus events to toggle the textbox type as either Password or Text. @Html.TextBoxFor(m => m.FinanceModel.VatNumber, new { @type = "password", @class = "form-control capitalize", maxlength = 30, @onblur = "setTypePassword(this ...

use ajax to dynamically load a section of the webpage based on filter criteria

I need to implement a search filter using 3 checkboxes. The search results will be displayed in the div with the id=posts_results <div class="checkbox"> <label><input type="checkbox" id="id1" class="typePost" value="En groupe"> ...

Obtain a child element using jQuery's nested selection feature

Is there a way to use jQuery to select the ul element nested within spans that come after the select element? <select id="my-select" class="my-select"> <option value="1">One value</option> ... </sele ...

Setting up only two input fields side by side in an Angular Form

I'm fairly new to Angular development and currently working on creating a registration form. I need the form to have two columns in a row, with fields like Firstname and Lastname in one row, followed by Phone, Email, Password, and Confirm Password in ...

Tips for efficiently utilizing a datatable in PHP with a substantial amount of data

After successfully implementing the jQuery plugin Datatable, I encountered a new challenge when working with a large dataset of 100000 rows. It takes around 10-15 minutes to load all the data. Can anyone provide suggestions on how to optimize the loading s ...

Customizable dropdown menu design using HTML and CSS

Hello everyone, this is my very first post on Stack Overflow and I'm a bit unsure about the rules regarding posting. Please feel free to point out any mistakes I may have made. I've searched through the forums but haven't found a clear answe ...

The (.svg) image does not cover the full width of the page

After creating an SVG image, I encountered a problem when trying to display it on a webpage. Even with the width value set to 100%, the image did not stretch all the way to the edges of the page, leaving small gaps at the edges. I attempted to switch the ...

Storing Array Data in Angular $scope (Javascript)

I am currently altering the Altair Material Design Template and incorporating an Angular JS controller. After successfully calling an API and creating variables in a for loop, I intend to write them to $scope.dragulaItems. While this process seems to work ...

Implementing JavaScript functionality with CSS and HTML on a menu

I'm experiencing issues with my website's menu functionality. Currently, the submenu dropdown works fine, but the main menu is not functional. How can I enable it on the main menu as well? document.addEventListener('click', function( ...

A common challenge in React is aligning the button and input line on the same level

I'm currently working on a React page where I have an input field and a button. My goal is to align the bottom edge of the button with the bottom line of the input. Here's the code snippet I have: `<form className='button-container'& ...

Complex design within bootstrap

Creating a complex layout in Bootstrap has been challenging for me. Whenever I remove the image on the right side, all other images resize, which is not what I want. How can I ensure that all the images maintain the same size regardless of how many are di ...

Making a PDF file download automatically upon clicking a button

Within my backbonejs view, there is a button labeled "download pdf" which when clicked should initiate the download of a PDF file from a specified URL. Is it feasible to implement this functionality? EDIT: Below is the code snippet from my Backbone.js vie ...

What is the best way to apply an active class to the parent li element when selecting an item within it? I want to achieve this effect

$(function() { var pgurl = window.location.href.substr(window.location.href .lastIndexOf("/") + 1); $("#nav ul li a").each(function() { if ($(this).attr("href") == pgurl || $(this).attr("href") == '') $(thi ...

Combine all div elements to create a unified image and then proceed to save it as a jpg file before uploading to the server

These are the divs below: <div style="width:800px; height:420px; position:absolute; top:0px; left:0px; z-index:10; background-image: url('https://3t27ch3qjjn74dw66o1as187-wpengine.netdna-ssl.com/wp-content/uploads/2016/05/052516-800x420-vege-Wallp ...

Retrieving data from an Ajax request

I am struggling with extracting the HP and PCP Payment fields from the JSON string obtained through a Jquery Ajax request: function DoPaymentSearch() { var start,end; start=Date.now(); var getQuotesSuccess = function(results){ end=Date.now(); alert(JSON.s ...

Hover over an element repeatedly to trigger an action with jQuery, as opposed to just once

Is it possible to have my p tag transition whenever I hover over it? I am looking to create a hover effect on an image that displays text in a div tag with scaling transitions. Can someone assist me with this? Instead of using jQuery or JavaScript to dyn ...

Multiple requests were made by Ajax

I am facing an issue with my ajax code where it is being called multiple times. Below is my php code: (While loop extracts results from a database. For brevity, I have included just the modal and dropdown menu sections.) $rezPet = mysqli_query($kon, "SEL ...

Modify the hue of the iron-icon upon being tapped

There's a simple example I have where my goal is to modify the color of an iron-icon when it's tapped. To achieve this, I'm utilizing iron-selector for tapping: <template> <style> :host { display: block; padding: 10 ...

The debate between centralization and specification: the ultimate Javascript/jQuery best practice for web applications

Picture a scenario where a web application consists of numerous page groups (pg1, pg2, ...) and some of these page groups require specific JavaScript code that is only relevant to them, not the entire app. For instance, certain visual adjustments on window ...

Displaying a small icon hyperlink when text is hovered over

Encountering an issue with getting a glyphicon link to appear when hovering over text. This specific div is in my HTML. <div class="editable container"> <h1>File Name: filename<a href="#"><span class="pencil glyphicon glyphicon-penci ...