Remove the class from all child elements and apply the class to the parent or ancestor of the element that was clicked on using

The Goal: I aim to achieve the following outcome. Whenever a user clicks on any of the radio inputs within the div that has the class corp-struct, I want to assign the following class to the parent element two levels up. This means that, in the example below, the class should be added to

<div class="radio radio-primary radio-button">
instead of the <label>. However, prior to this action, I want to remove this same class from any divs within the corp-struct element.

Everything is functioning as expected except for the removal of class names from other child divs.

let $e = $(e.currentTarget);
if ( $e.hasClass('checked-radio-button')){
$e.parent().parent().removeClass('checked-radio-button')
} else {

$("div#corp-struct>div.radio-button").removeClass('checked-radio-button');
$e.parent().parent().addClass('checked-radio-button');

}

The Query: I only want to append the above class to the element if it hasn't been added already. Simultaneously, I want to ensure that the class is removed from the other three elements within

<div id="corp-struct" class="radio-group container-fluid">
. Additionally, if I click on a radio that already has the class, it should be removed from that particular one.

**Sample HTML:**

<div class="radio-group container-fluid corp-struct">
                    <h6>Page Title</h6>

                    <div class="row">
                        <div class="col-md-12">
                            <div class="radio radio-primary radio-button">
                                <label>
                                    <input type="radio" name="corpStructure" id="corpStructure_subset" value="subset" {{#eq corpStructure "subset"}}checked{{/eq}}></input>
                                    <span class="circle"></span>
                                    <span class="check"></span>
                                    <span class="radio-button-text">{{nls "organization_corpStructure_subset"}}-{{corpStructure}}</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="radio radio-primary radio-button">
                                <label>
                                    <input type="radio" name="corpStructure" id="corpStructure_subsidiary" value="subsidiary"></input>
                                    <span class="circle"></span>
                                    <span class="check"></span>
                                    <span class="radio-button-text">{{nls "organization_corpStructure_subsidiary"}}</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="radio radio-primary radio-button">
                                <label>
                                    <input type="radio" name="corpStructure" id="corpStructure_single" value="single"></input>
                                    <span class="circle"></span>
                                    <span class="check"></span>
                                    <span class="radio-button-text">{{nls "organization_corpStructure_single"}}</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="radio radio-primary radio-button">
                                <label>
                                    <input type="radio" name="corpStructure" id="corpStructure_parent" value="parent"></input>
                                    <span class="circle"></span>
                                    <span class="check"></span>
                                    <span class="radio-button-text">{{nls "organization_corpStructure_parent"}}</span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>

My Current Progress:

Upon clicking a radio, the class is added correctly. Furthermore, clicking on it again removes the class appropriately. However, if I click on one radio and then on another, both end up having the class instead of only the initial one getting it removed.

Answer №1

If I understand your issue correctly, you can achieve the desired outcome with the following code:

var $element = $(element.currentTarget),
    $div = $element.closest('div.radio-button'),
    $container = $element.closest('.corp-struct');

    $div.toggleClass('checked-radio-button');

    $('div.radio-button.checked-radio-button', $container).not($div).removeClass('checked-radio-button');

Here is a breakdown of the code:

First, obtain a jQuery object reference of the clicked radio button:

var $element = $(element.currentTarget)

Next, get a reference to the div containing the radio button (closest will traverse up the DOM tree until the first element with the specified selector is found):

$div = $element.closest('div.radio-button')

Then, obtain a reference to the overall .corp-struct container:

$container = $element.closest('.corp-struct');

Toggle the class of the container div:

$div.toggleClass('checked-radio-button');

Lastly, remove the class from any other divs within the $container that are not the current div:

$('div.radio-button.checked-radio-button', $container).not($div).removeClass('checked-radio-button');

Does this explanation help?

Take a look at this fiddle for a demonstration

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

When utilizing a Javascript event listener within ReactJS with NextJS, the dynamically imported module without server-side rendering fails to load

Hello everyone, I am new to ReactJS and NextJS and would really appreciate some advice on the issue below. Thank you in advance! Here is my current tech stack: Node v16.6.1 React v17.0.2 Next.js v10.0.4 I'm working on implementing a carousel and si ...

Modifying the HTML5 data attribute according to the URL hash

Within my div element, I have this code: <div id="nav-aj" data-options='{"default":'t1","animation": {"duration": 500, "effects": "fade"}}'> </div> I am looking to dynamically adjust the value of the default option based on th ...

text field remaining populated

I have a form where the input fields clear when they are clicked on. It works well on most pages, but there is a specific type of page where it is not functioning properly due to the presence of another javascript running. - issue observed // On this pa ...

Troubleshooting Issue with React Function's Conditional Component Rendering

Currently, I am working on honing my skills in React using Codesandbox. My goal is to conditionally display a functional React component inside a function (within a class-based component) that triggers when a button is clicked. If you'd like to take ...

Could there be any issues with the structure of my mongoose schema?

I've been stuck for 3 hours trying to solve this problem. I can't seem to retrieve any data from my document. var mongoose = require('mongoose'); var Schema = mongoose.Schema; var accountSchema = mongoose.Schema({ username: String ...

Unable to save or create files in Store.js

Recently, I've been trying to save a file on client storage using Store.js. After changing the date with store.set and logging it to the console successfully, I encountered an issue where the data was not being saved in the app directory as expected. ...

The solution to enabling multiple inputs when multiple buttons are chosen

Below is a link to my jsfiddle application: http://jsfiddle.net/ybZvv/5/ Upon opening the jsfiddle, you will notice a top control panel with "Answer" buttons. Additionally, there are letter buttons, as well as "True" and "False" buttons. The functionali ...

Utilizing a GET method with MongoDB

My front end has a link using axios with a placeID parameter: http://localhost:3001/api/getData?placeID=Uh8LPCRstLnJ-ZY3B41N9w I am trying to retrieve results based on the placeID in my database. I have made sure that there is data with the specific place ...

Tips for sending multiple variables in a loop as JSON data through an AJAX request

I need assistance with the code below. I am trying to pass the value[i] into a data string in a json ajax post submit. Essentially, my goal is to gather all the checked values in a form and insert them into an existing json data string using ajax. This is ...

How can I incorporate a custom color into a preset navbar on an HTML webpage?

<div class="navbar-header"> <button aria-controls="navbar" aria-expanded="false" data-target="#navbar" data-toggle="collapse" style="color: blue;" class="navbar-toggle collapsed" type="button"> <i class="fa fa-reo ...

Searching for mobile WiFi preferences through a web browserHere are the steps to

Is there a method to access mobile connectivity settings through a website? I am interested in determining the connection type (3G\4G\WiFi) and if it is WiFi, identifying the security method being used. Is this achievable? If so, how? Edit: If ...

What should I do to resolve the issue of the function if ($(window).width() < 768) {} not functioning properly upon resizing the browser?

I am working on a functionality where the navigation bar items will toggle hidden or shown only when the browser width is less than 768px and an element with the class "navlogo" is clicked. I have included my code below for reference. if ($(window).width( ...

Issue with conditional comment in IE 8 not functioning as expected

Struggling with changing the SRC attribute of my iFrame specifically for users on IE 8 or older. This is the code I have written: <script> var i_am_old_ie = false; <!--[if lte IE 8]> i_am_old_ie = true; <![endif]--> </script> ...

Angular 9 Singleton Service Issue: Not Functioning as Expected

I have implemented a singleton service to manage shared data in my Angular application. The code for the service can be seen below: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataS ...

Steps for aligning a grid column to the same height as the element above it and moving it to the left side

I have a setup using material UI where I have a grid positioned on top of a Paper element. Within the grid, there is a text input field in the first column that I want to match the height of the paper element and be aligned with its left border. I have tri ...

What is the process for generating an attribute in a system?

If I want to create an element using plain JavaScript, here is how I can do it: var btn = document.createElement('button'); btn.setAttribute('onClick', 'console.log(\'click\')'); document.body.appendChild( ...

Place a small image within a list item to ensure it matches the height of the list element

I need help aligning images to the right within list elements. The images are squares with equal height and width, and I want them to fit snugly within the height of the list element on the right side. My HTML code is quite simple for now (see example bel ...

What is the method for utilizing Jquery to target the width value of an inline property?

I am struggling with selecting the "style=:width: 10%" value using jquery for a progress bar element in bootstrap. <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 10% ...

Running a function following several iterations of angular.forEach

let values1 = [1, 2, 3]; angular.forEach(values1, function(value){ $compile(value)($scope); }); let values2 = ['a', 'b', 'c']; angular.forEach(values2, function(value){ $compile(value)($scope ...

How can I utilize JQuery to dynamically refresh a dropdown menu?

My dropdown list is initially empty: <div> <label>Boarding Point </label> <select title="Select pickup city" id="boardingDropdown"> </select> </div> I am trying to popula ...