Apply the active class to only one element at a time

Presented here is a table showcasing available dates and times. Users can select a specific time by clicking on the "Choose" link. Currently, when a user selects a time, the class "active" is applied. However, the desired behavior is to remove the previous class and apply it to the newly selected element.

Here is the current structure:

<div class="wrapper-div">
    <div class="row">
        <div class="date">monday, 2015 09 02 </div>
        <div class="time">12:10</div>
        <div class="select"><a href="#">Choose <span class="select-arrow"></span></a>            
   </div>
    </div>
    <div class="row">
        <div class="date">thuesday, 2015 06 22</div>
        <div class="time">12:30</div>
        <div class="select"><a href="#">Choose <span class="select-arrow"></span></a></div>
    </div>
    <div class="row">
        <div class="date">wensday, 2015 02 9</div>
        <div class="time">09:15</div>
        <div class="select"><a href="#">Choose <span class="select-arrow"></span></a></div>
    </div> 
</div>

Implemented jQuery code:

$('.select a').click(function(e){
    e.preventDefault();
    $(this).parents().eq(1).addClass('active');
    $('.wrapper-div div').each(function(){
        removeClass('active');
    });
});

Refer to this working fiddle for an interactive example:

Seeking advice on the most effective solution for this scenario.

Answer №1

The usage of the each function in your code snippet is not correct since you are not applying removeClass to any jQuery object. Moreover, the inclusion of each seems unnecessary. Consider the following revised approach:

$('.select a').click(function(e){
    e.preventDefault();
    $('.wrapper-div div').removeClass('active'); // remove previous active
    $(this).parents().eq(1).addClass('active');
});

Answer №2

check out this updated solution http://jsfiddle.net/gtog33qk/2/

$('.select a').click(function(e){
    e.preventDefault();
    $('.wrapper-div div').each(function(i,e){
        $(e).removeClass('active');
    });
    $(this).closest('.row').addClass('active');

});

I made some tweaks to the code, utilizing closest to target the entire active row and applying removeClass on an element, following Rory's guidance.

Answer №3

To locate the specific class for removal, consider utilizing jQuery's .find() method combined with jQuery's .remove() method for deletion. Once the targeted class has been removed, simply append your desired .active class.

Answer №4

To successfully toggle the "active" class, start by adding the new class and then removing all existing instances of "active." This ensures that only the clicked element will have the class applied.

$('.container-div .item').each(function(){
    $(this).removeClass('active');
});
$(this).parents().find(".item:first").addClass('active');

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

How can I trigger a function by clicking on a link that was generated dynamically with jQuery?

I am dynamically creating multiple <a href="#"></a> elements with dynamically assigned id attributes like <a href="#" id='delete"+id+"'></a>. The IDs generated will be like delete01, delete02, .... I want to trigger a func ...

What are some methods to manage the state of Bootstrap 4 modals in React without using jQuery?

Creating a PHP web app with Twig templates has been my latest project. Recently, I've been incorporating ReactJS components for some new forms and replacing existing ones, and I am quite pleased with the outcome. Bootstrap 4 is the framework used for ...

Expanding a div's size with CSS to fill the remaining space

Here's the setup I'm working with: <div class="parent"> <div class="moverBoy"></div> <div class="smartBoy"></div> </div> The parent element is fixed at 100x20 indefinitely. moverBoy and smartBoy are al ...

Assigning a height of 100% to a div element results in the appearance of

In a div within the body, there are only 3 lines of text. The background color was only filling up to those 3 lines of text. To make the color fill up the entire vertical space of the browser, I adjusted the CSS height properties of html & body to be ...

Unable to close Bootstrap sidebar menu on mobile devices

I implemented a sidebar menu for mobile that opens when you click on the hamburger icon, with a dark overlay covering the body. The issue I encountered is that on mobile devices, the visibility of the menu does not change when clicked outside of it. It wor ...

Replacing variables in a function: A step-by-step guide

I have frequently used the replace function to eliminate classes in JavaScript. Currently, I am working on creating a JavaScript function that allows me to remove a specific class from an element by passing in the element and the class name. changeAddress ...

Remove identical options from the dropdown menu

After hard-coding and adding items to the dropdown list for team size, such as 1, 2, 3, I am encountering an issue when loading it for editing or updating. Duplicate values are appearing in the list: 1 1 2 3 4... How can I remove these duplicate value ...

What are the possibilities for modifying a MySQL database using HTML?

Currently, I have a MySQL database managed through phpmyadmin that I would like to present as an HTML table for easy editing of records and columns directly. I am unsure about the terminology to use when researching possible solutions. What options are av ...

Scale transformation - I am aiming for it to exceed the limits, yet it remains contained within

Currently, I am working on enhancing my carousel by implementing a zoom effect when hovering over the images. However, I have encountered an issue where the image gets hidden within the div container and doesn't overflow as expected. I tried adjusting ...

Tips for loading a webpage with optimal speed and efficiency

I am inspired by the sleek design of Apple's website and want to replicate some of its features in my project (best viewed on FF, Chrome, Safari): Initially, the page appears empty except for the header - but the final height of the page is already ...

Design: Seeking a layout feature where one cell in a row can be larger than the other cells

To better illustrate my goal, refer to this image: Desired Output <\b> Currently, I'm achieving this: current output Imagine 7 rows of data with two columns each. The issue arises in row 1, column 2 where the control needs to span 5 row ...

The tbody element fails to occupy the full width of the table, leaving the content exposed

HTML: <body class="header"> <div class="container-fluid"> <div class="container d-flex justify-content-center"> <p class="display-3">Secure Vault</p> < ...

Only output to the console if the data returned from an AJAX request has been

Here is a script that I created: <script type="text/javascript> $('.storage').html(""); setInterval(function(){ $.get('./playcommand.php', function(data) { if($('.storage').html() !== data){ ...

Tips for adjusting the size of a container to fit its child element in a flexbox layout, where the flex-direction is set to column

Below is the functional code: .container{ display: flex; background-color: lightgreen; justify-content: center; alighn-item: center; } .child{ margin-left: 10px; height: 200px; background-color: yellow; display: flex; flex-direction: ...

Ways to retrieve the file name and additional attributes from a hidden input type

Is it possible to access the file name and other attributes of a hidden file when submitting it using the <input type="hidden"> tag? My current project involves drag and drop file functionality on a server using Node.js. If I am able to dynamically ...

Is it necessary for me to employ MetaTag http-equiv in conjunction with DTD XHTML 1.0 Transitional//EN?

Currently using Asp.net for my project. In the document, I have included the following: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> I am wondering if it is necessary to a ...

Exploring cross-browser compatibility with the use of CSS3 and JavaScript

Starting a new project to create a fresh website. It seems like many people are leaning towards CSS3 and AJAX, neglecting browsers without JavaScript support. They resort to workarounds like enabling CSS3 through JavaScript in older browsers. Is this the ...

Canvas flood fill is having trouble reaching the edges

While utilizing a flood fill algorithm to fill circles drawn on the canvas, I've encountered an issue where the algorithm fails to fill right up to the edge of the circle. Here is the implementation of the algorithm based on this blog post: function ...

Having trouble verifying the selection option in Angular 6

I've been trying to implement Select option validation in Angular 6, but neither Aria-required nor required seem to be effective. The requirement is for it to display a message or show a RED border similar to HTML forms. Here's the HTML snippet ...

Parallax not functioning properly due to CSS before and after elements

I am attempting to use before and after pseudo-elements for a parallax effect on my div element <div id="OurPhilosophy" class="parallax-window" data-parallax="scroll" data-image-src="https://cdn6.bigcommerce.com/s-jhmi7y5v2c/product_images/uploaded_ima ...