Is it possible to change the button class within a div while ensuring only the last one retains the change?

Here is a code snippet I'm using to switch between classes for buttons:

$('button').on('click', function(){
    var btn=$(this);
    if(btn.attr('class')=='tct-button'){
        btn.removeClass('tct-button').addClass('tct-button2');
    }
    else{
        btn.removeClass('tct-button2').addClass('tct-button');
    }

});

I need help with modifying this code so that when I click on a button in a div, any other buttons within the same div that were changed previously revert back to the default class 'tct-button'. Only the most recently clicked button should have the 'tct-button2' class. Can you assist me with this modification?

Answer №1

Utilize the toggleClass function in jQuery instead of using hasClass()

$(this).toggleClass("custom-button1 custom-button2");

See Example

Answer №2

Check if any of the selected elements have a specific class using hasClass()

Determine whether any of the matched elements have been assigned the specified class.

Example Code

$('button').on('click', function(){
    var btn = $(this);
    if(btn.hasClass('tct-button')){
        btn.removeClass('tct-button').addClass('tct-button2');
    }
    else{
        btn.removeClass('tct-button2').addClass('tct-button');
    }       
});

Another approach could be

$('button').on('click', function(){
    $('.tct-button2').removeClass('tct-button2'); //Remove all instances of this class 
    $(this).addClass('tct-button2'); //Add the class to the current element
});

Answer №3

To enhance your buttons with an extra class (tct-button2) while maintaining the original tct-button class on all buttons, you can follow Satpal's suggestion.

However, if you're looking to update the classes so that each button only has one class at a time (either tct-button or tct-button2), you can adopt a similar approach as suggested by Satpal:

$('button').on('click', function(){
    $('.tct-button2').addClass('tct-button').removeClass('tct-button2'); //Add original class and Remove tct-button2 class
    $(this).removeClass('tct-button').addClass('tct-button2'); //Apply class to current element
});

Here is an example http://jsfiddle.net/lee_gladding/xao46uzs/

If you want to target only the buttons within the same div as the clicked button, you can use a method like this:

$('button').on('click', function(){
    $(this).parent('div').find('.tct-button2').addClass('tct-button').removeClass('tct-button2'); //Remove all classes in that div
    $(this).removeClass('tct-button').addClass('tct-button2'); //Apply the class to current element
});

(Consider using a more precise selector for the parent element, such as a class or whatever structure your HTML follows)

Example:

http://jsfiddle.net/lee_gladding/xao46uzs/3/

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 v-show directive is not activated by a Vuex commit

I am experimenting with vuex for the first time, and I have come across an issue where a v-show directive is not triggering after a mutation commit on the store. // store.js import Vue from "vue" import Vuex from "vuex" const states = ...

The @media print rule for Angular 16 in the style.css file is not functioning properly

I'm currently working on an Angular component called ViewTask, which has a template that is rendered inside the app component. The app component also consists of a side nav bar. My goal is to only display the content inside the 'print-section&apo ...

Unlock the Power of TWBS Ratchet: Manually Closing Modal Windows

Currently, I am in the process of developing a mobile web application using Ratchet. The main task at hand involves opening a modal, filling out a form, clicking a button to save the input data, and then closing the modal. Although I have managed to close ...

Customizing the appearance of Indicators and Paginator in PrimeNG Carousel

I have integrated a carousel using PrimeNG which has the following design here Take note of the style of the carousel indicators and navigators. I want to achieve the default style of indicators/navigators for the carousel as shown here I have included t ...

Tips for resolving the error "React import attempt":

I'm a beginner in learning React and I encountered this error when trying to export NavigationMenu and import it into Navigation: Failed to compile ./src/components/Navigation.js Attempted import error: 'NavigationMenu' is not exported from ...

When attempting to call a Firebase Cloud Function URL in an AngularJS $http request, an Access Control Origin Error

I recently created a cloud function that involves linking with Plaid. I'm currently working on calling this function using AngularJS's $http method. While the cloud function code is being executed, I encountered an error in my console instead of ...

React: Submit button not triggering form submission despite having a valid submit event handler and correct syntax

My question stands out from existing ones as it features valid syntax, correct use of type="submit" on the button, and a simple onSubmit handler on the form. Despite this, clicking the button fails to trigger the onSubmit handler. To illustrate ...

Is it possible for Websockets to receive data from Ajax requests?

I am currently working on creating a PHP and HTML5 websocket chat system. In this setup, one end will be a socket while the other end will be AJAX. Is it possible for PHP's socket_recv() function to receive data from sources like AJAX, MySQL, or any o ...

How can I retrieve routing parameters in a Vue.js/Nuxt/TypeScript app?

In the process of developing my website based on the Nuxt TypeScript Starter template, I've encountered a challenge. Specifically, I have created a dynamically routed page named _id.vue within my pages folder and am looking to access the id property i ...

How to Incorporate LessCSS into the Blueprint Framework?

Can LessCSS be integrated with Blueprint framework? What are the prerequisites for starting? ...

Can you provide me the steps to delete the title attribute from images in Wordpress?

My client has expressed dissatisfaction with the tooltip that appears when hovering over images in certain browsers, particularly Safari. This tooltip displays the title attribute within the img tag, which is a requirement enforced by Wordpress. Even if w ...

Using jQuery to display a div after a 2-second delay on my website, ensuring it only appears once and does not reappear when the page is refreshed or when navigating to a

I manage a website that includes a blog section. Every time someone visits the site, I want a popup window to appear. (To achieve this, follow these steps - Utilize jQuery for showing a div in 5 seconds) I would like this popup to only be displayed once ...

Ensuring the selected date matches any consecutive dates within the dates array in Angular

Imagine if 01/01/2022 is chosen from the input field, and my array of dates looks something like this: ['31/12/2021', '01/11/2021', '02/01/2022'...] In this scenario, when '31/12/2021' and '02/01/2022' are ...

Enhancing the content of a field - React

Seeking assistance with populating an input field with a generated password in my React component. Currently, the password is showing as undefined. MainComponent.js - primary React component class MainComponent extends React.Component { state = { p ...

I possess information stored within the array object below, and I aim to transform it into a different array object format

Here is the response I received from my API: let data = [ { date: '2021-04-27', formatted_date: 'Apr 27', location: [ { date: '2021-04-27', formatted_date: 'Apr 27', countr ...

Managing data flow in React and Reflux: Utilizing a single component duplicated in the DOM

Imagine this Tree scenario: <Homepage> <HeaderSection> <Navbar> <ShoppingCartComponent> </Navbar> </HeaderSection> <MainContent> <ShoppingCartComponent> &l ...

Chrome method for creating Flexbox columns of equal height

I am implementing a simple 2-column layout and I want to utilize Flexbox to ensure equal heights for the columns: HTML <div class="row flex"> <!-- menu --> <div class="col-xs-4"> <aside> Menu content wi ...

Challenge with CSS3 Selectors

I'm struggling to understand why this code works: input[ type = "text" ]:last-of-type:focus{ border:1px solid red; } but this code doesn't work: input[ type = "checkbox" ]:last-of-type:checked{ border:1px solid red; } The example given with t ...

When clicking in JavaScript, there are two parts to the function, however only one part will work at any given time

I am currently working with two server-side PHP scripts: 1. /addit.php - which generates a PDF file on the server based on the provided ID 2. /viewit.php - which allows the PDF file to be downloaded to the browser window. While both of these scripts are ...

Conceal the initial modal beneath the overlay when the second modal is activated

I have a situation where I am using a modal that contains a button to trigger a second modal. The issue is that the overlay of the second modal does not hide the first modal, it simply darkens the background. How can I make the overlay of the second modal ...