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

Having issues with handling ajax response in a Node.js application?

I am encountering an issue with my ajax post request to my node js backend. After sending the request and receiving a response, instead of updating just the resulttoken in the view, the entire HTML page seems to be loaded according to the console. I am see ...

Creating an Editor for Input Text Field in HTML: A Step-by-Step Guide

In the vast landscape of JS libraries that can achieve this function, like Trumbowyg and more. However, prior to my rails project displaying that slim version, I need to ensure JavaScript is properly escaped! Therefore, I need to create an editor using o ...

Utilizing AngularJS to filter prices within a specific range using a button

I am new to using angularjs and I am working on implementing a price range filter with nouislider for a list of products with different prices. I want the filtering to happen only after the user clicks on the filter button. Below is the HTML code for my " ...

Having trouble implementing Bootstrap Progress Bar with AJAX in webpy

I am currently working on a web application using webpy and dealing with a Bootstrap progress bar in the template HTML file. To update this progress bar dynamically, I aim to utilize jQuery AJAX calls to fetch data from the server. In order to achieve thi ...

Arrange two divs with a full width of 100% next to each other

Is there a way to create two divs, each taking up 100% of the page width and side by side within a wrapper with overflow:hidden? How can I achieve this? I attempted using inline-block, but it didn't produce the desired outcome. Similarly, when I tri ...

Convert alias query strings into parameters

I am currently working on a project that involves using node, express, and jade. I need to be able to access content through two different URLs: /Page/foo/bar and /Page?Foo=foo&Bar=bar The goal is for the top URL to act as an alias for the bottom o ...

What is the reason border-box does not function properly on inline-block elements?

Demo: http://jsfiddle.net/L5jchnpm/ I've encountered an issue where I believed that using display: inline-block would make elements act as both inline and block elements. Additionally, I thought that setting box-sizing: border-box would adjust the w ...

The attribute in the JSON response from jQuery is incorrect and does not comply

I need to retrieve data from a different server and I am implementing an authentication method using jQuery. The expected data format from the server should be in JSON, but I'm encountering an error stating "invalid XML attribute value" in Firebug. M ...

I'm seeking guidance on how to delete a specific ul li element by its id after making an ajax request to delete a corresponding row in MySQL database. I'm unsure about the correct placement for the jQuery

I have created an app that displays a list of income items. Each item is contained within an li element with a unique id, along with the item description and a small trash icon. Currently, I have implemented code that triggers an AJAX call when the user cl ...

Transform a nested JSON Object into a customized array structure

My task involves converting a nested JSON object into a specific format, as demonstrated below: let jsonObj ={"data": { "cardShop": { "cardData": { "cardTitle": "The Platinum Card<sup> ...

Modifying the appearance of Bootstrap 4 Nav-tabs using CSS

I have implemented Bootstrap 4 Nav-tabs as shown below: <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" ...

Troubles with importing/resolving components in Vue 3

Just starting out with Vue and following tutorials to learn. I've created a component called Header.vue and attempted to import it into App.vue. This is the setup: code structure Here is App.vue: <template> <Header /> </template&g ...

Convert numerical values to currency format

Here is a number 5850 that I would like to format as currency. Format Example 1: 5850 => $58.50 Format Example 2: 9280 => $92.80 I am utilizing the function below: Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparat ...

Storing the time that a video has been played in a Laravel database

Managing a users table and lesson table involves storing the data of current playing lesson_id and currentTime in the watch_history column of the users table. This allows users to resume watching from where they left off or skipped. As a beginner with AJA ...

Is the admin_init hook in Wordpress triggering multiple times?

Encountering an issue on my Wordpress website where admin_init is being called twice has been quite a headache. After deactivating all plugins, I managed to pinpoint the culprit plugin that was causing the problem. Now my dilemma is how to determine the ...

Retrieve JSON data with a GET request and populate an array with the results before returning

Recently, I delved into using the mobile framework LungoJS. Although my experience with JavaScript is limited, I am determined to make changes to the following original code: ORIGINAL.JS var mock = function() { var mock = []; for (var i=1 ...

Accessing an item within a JSON object using jQuery

Trying to access an element within a JSON object, part of the code is shown below: { " academy": { "business": { "E-commerce": [ I have successfully accessed the academy as the first element using the following code: $.getJSON("p ...

Issue with npm installation leading to missing node_modules directory

When attempting to run npm install . in a local directory, I keep encountering the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 15.2.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "." npm ERR! no ...

Make the adjustment from an H1 tag to an H2 tag with the help of

I need assistance with changing the HTML code from using an <h1> tag to a <h3> tag, using Vanilla JavaScript. Here is the code snippet in question: <h1 class="price-heading ult-responsive cust-headformat" data-ultimate-target=" ...

What exactly does the dollar sign signify in plain JavaScript code?

While watching a tutorial on object literals in JavaScript, I noticed something interesting. The instructor demonstrated creating an object like this: var Facebook = { name: 'Facebook', ceo: { firstName: "Mark", favColor: ...