How to dynamically assign a CSS class to the parent <li> element when a radio button is selected using JavaScript

I am facing a challenge with a form that includes multiple series of input fields created dynamically by a plugin. The structure of the code is as follows:

<!-- section 1 -->
<div>
    <ul>
        <li>
            <input type="radio" name="wccf[product][people]" id="wccf_product_people_one" class="wccf wccf_product wccf_radio wccf_product_radio"></input>
        </li>
        <li>
            <input type="radio" name="wccf[product][people]" id="wccf_product_people_twp" class="wccf wccf_product wccf_radio wccf_product_radio"></input>
        </li>
        <li>
            <input type="radio" name="wccf[product][people]" id="wccf_product_people_three" class="wccf wccf_product wccf_radio wccf_product_radio"></input>
        </li>
    </ul>
</div>

<!-- section 2 -->
<div>
    <ul>
        <li>
            <input type="radio" name="wccf[product][budget]" id="wccf_product_budget_one" class="wccf wccf_product wccf_radio wccf_product_radio"></input>
        </li>
        <li>
            <input type="radio" name="wccf[product][budget]" id="wccf_product_budgete_twp" class="wccf wccf_product wccf_radio wccf_product_radio"></input>
        </li>
        <li>
            <input type="radio" name="wccf[product][budget]" id="wccf_product_budget_three" class="wccf wccf_product wccf_radio wccf_product_radio"></input>
        </li>
    </ul>
</div>

My goal is to apply the .checked class to the <li> elements that contain a checked radio button.

I have made some progress in achieving this functionality, but I am encountering an issue where selecting an element in one section causes the previously selected element in the other section to be unchecked and vice versa.

// Radio buttons for PEOPLE
$('input[name="wccf[product][people]"]').on('click', function() {
    $(".checked").removeClass("checked");
    $(this).parent().toggleClass("checked");
});

// Radio buttons for BUDGET
$('input[name="wccf[product][budget]"]').on('click', function() {
    $(".checked").removeClass("checked");
    $(this).parent().toggleClass("checked");
});

Answer №1

Loop through all the checkboxes and apply the correct classes when each one is changed, etc.

let checkboxList = $('.wccf_product_radio').on('change', function() {
    checkboxList.filter(':checked')
         .closest('li')
         .addClass('checked')
         .siblings('li')
         .removeClass('checked');
});

Answer №2

There seems to be an issue with the selector $('.checked'). It appears that this selector is not specifically targeting the content within a certain ul element. Instead, it is searching through the entire DOM for the class, removing it, and then adding it to the current parent. To resolve this problem, consider modifying your code as follows:

$('input[name="wccf[product][people]"], input[name="wccf[product][budget]"]').on('click', function() {
    $(this).parent()
        .siblings('.checked')
        .removeClass('checked')
        .end()
        .addClass('checked');
});

Additionally, please keep in mind that the <input /> element is self-closing and does not require a closing tag like </input>.

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

Creating a personalized animation user interface for an ExtJS message box is a great way to enhance

I want to display a customized message box in extjs with a unique user interface. I have experimented with Ext.MessageBox.show and Ext.Msg.wait functions for this task. My specific requirement is to exhibit a custom "Loading" image instead of a static rect ...

My code is throwing an issue related to unhandled promise rejection that I need to address

Encountering an issue with an Unhandled promise rejection while trying to save a document staged in a mongodb document. How can I resolve this error? https://i.sstatic.net/ObfaG.png ...

Issue with page refreshing not functioning on localhost in Rails and AngularJS collaboration

I recently encountered a strange issue while working on my Rails 4.2 + AngularJS 1.5 project. Whenever I attempt to refresh (F5) the main web-page, there's about a 9 out of 10 chance that the refresh doesn't happen correctly. In these cases, all ...

Variable from the submitted form does not contain the expected data

Even though I struggled to find a solution for this issue, I decided to share it here. Whenever I attempt to retrieve data from a form-submitted variable $receiptNo, it just doesn't seem to work. sales.php <input name="txtReceiptNo" type="text" i ...

Convenient methods in Three.js for easily detaching and attaching character weapons within a scene

I'm currently facing challenges while developing a first-person shooter game using Three.js. I've encountered major glitches with THREE.SceneUtils.detach() and THREE.SceneUtils.attach(), and I'm uncertain if they are the appropriate methods ...

When I hover over one menu item, it interferes with my CSS transitions because the other menu items are hidden

I've been attempting to create a menu with very specific behavior: 1) Submenu transitions in when its corresponding menu item is hovered over 2) Submenu remains visible for a moment after moving the mouse away before transitioning out 3) If another me ...

JavaScript consistently returns HiddenField as NULL

After creating a Context menu and associating it with a Gridview, I noticed a problem when pressing a button from the context menu. I intended to retrieve a value from a HiddenField, but it always returns null. My assumption is that the DOM might not be fu ...

What are the limitations when using React's forwardRef with Material UI's styled components?

While working with forwardRef and styled, I encountered a strange issue : "React Hook ... cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function." Here is an example: import { styled } ...

The jQuery slider comes to a gradual halt

I can't figure out why my jQuery slider doesn't stop right away after a mouseover event. There seems to be a delay that I can't resolve on my own. Can someone lend a hand with this problem? Here is the code I'm working with: https://js ...

"Revolutionize Your Site with Endless Scrolling using q

I am currently in the process of developing a web application using create-react-app along with the packages Infinite-Scroller and qwest. (https://www.npmjs.com/package/react-infinite-scroller) (https://www.npmjs.com/package/qwest) This is how my code l ...

Creating a slick progress bar using a combination of HTML, CSS, and JavaScript

Looking to create a progress bar similar to the one shown in the image below? https://i.sstatic.net/dwrDp.png ...

Is there a way to monitor the home button press event within a PhoneGap application?

Hello! I'm curious if there is a way to track when the Home button is pressed on both Android and IOS using phonegap phonegap build. I have looked into events for the home button press, but have only found information on back button events so far. ...

Is Angular 4 having trouble with certain video file extensions for video previews?

I'm currently facing an issue with video previews. I am able to display mp4 file extensions for the preview, but other file extensions like mpeg, m4v, wmv, etc. are not working with the current code. Even though I added all file types in the video sr ...

utilizing AJAX to retrieve information from a database

Every time I run this code, it triggers the error function OnError instead of calling the success function OnSuccess. I am unable to figure out why. JS: $(document).ready(function () { // Retrieving data on button click $( ...

Navigating to a specific element with a smooth scroll in Angular after changing states

While working in Angular, I'm utilizing a node package to enable smooth scrolling on my website. One challenge I'm facing is implementing a feature where clicking on a link in the navbar while on a specific history state will take the user to tha ...

How can IF and ELSE IF statements be used in JavaScript?

I am struggling to figure out the correct and efficient way to implement IF and else IF statements in javascript. Here is my current challenge... Currently, I am combining the values of 2 input fields and displaying them in another input field like this: ...

JavaScript: exporting everything from ... causing excessive bloat in the build file

After building my react-app with create-react-app, I noticed a decline in performance. Here is the structure of my project: /store actions.ts reducers.ts /module1 module1.actions.ts module1.reducers.ts /moduleN moduleN.actions.ts m ...

The necessary parameters are not provided for [Route: bill] [URI: bill/{id}]

I'm having trouble locating the error in my code. Here is my controller: public function editBill(Request $req) { $customerInfo=Customer::where('id',$req->id)->first(); $billInfo=Bill::where('id',$req->id)->get( ...

Nothing remains after the fall: coding void

I am facing an issue where my item becomes null after being dragged 2-3 times and dropped in a different place. I have included my code below and I can't seem to figure out where the mistake lies. Can you please review it and let me know what needs to ...

Chat lines in Chrome displaying double entries - troubleshooting needed

I developed a chat plugin for my website with a simple HTML structure: <div id="div_chat"> <ul id="ul_chat"> </ul> </div> <div id="div_inputchatline"> <input type="text" id="input_chatline" name="input_chatline" val ...