Tips for updating the class of a button upon clicking it

I have a dilemma with my two buttons - one is green and the other has no background. I want them to change appearance when clicked, from green to one with a dashed border-bottom style.

Below is the HTML code for these buttons:

 <div class="btns">
                <button type="button" class="btn btn-success">Male</button>
                <button type="button" class="btn btn-link btn-simple">Female</button>
           </div>

I attempted to write a script to achieve this functionality:

$('.btn').click(function() {
    var $this = $(this);
    if ($this.hasClass('btn-success')) {
        $this.removeClass().addClass('btn-simple');
    } else if ($this.hasClass('btn-simple')) {
        $this.removeClass('btn-simple').addClass('btn-success');
       }
});

Unfortunately, it seems that the script is not working as expected.

In addition, here is the CSS styling added for the button with the dashed border effect:

.btn-simple {
    border-bottom: 1px dashed #000;
    color: #000;
}

No other additional styles were applied since these buttons are utilizing Bootstrap styling.

Answer №1

It is recommended to include your code inside the document.ready method for proper execution.

$(document).ready(function () {
        $('.button').click(function () {
            var $this = $(this);
            if ($this.hasClass('btn-primary')) {
                $this.removeClass().addClass('btn-secondary');
            } else if ($this.hasClass('btn-secondary')) {
                $this.removeClass('btn-secondary').addClass('btn-primary');
            }
        });
    });

Answer №2

To remove a specific class, you should use the following syntax: $this.removeClass('btn-success'). See the example provided in the link below for more clarity.

   $('.btn').click(function(){
       var $this = $(this);
       if (!$this.hasClass('btn-success')) {
        $('.btn').removeClass('btn-success')
        $this.addClass('btn-success');

       }
    })

https://codepen.io/jmejia1221/pen/qMwLQP

Answer №3

You forgot to remove the btn-success class and add the btn-link class. Make sure to wrap this code inside document.ready for it to work properly.

$(document).ready(function () {
    $('.btn').click(function() {
        var $this = $(this);
        if ($this.hasClass('btn-success')) {
            $this.removeClass('btn-success').addClass('btn-simple');
        } else if ($this.hasClass('btn-simple')) {
            $this.removeClass('btn-simple').addClass('btn-link').addClass('btn-success');
           }
    });
});

Answer №4

If you're looking to switch between buttons in a common container, you can use the following jQuery code:

/* A demonstration of toggling between buttons */
$('.btn').click(function() {
  var thisParent = $(this).closest('.btns');
  $(thisParent).find('.btn-success').addClass('btn-simple')
  $(thisParent).find('.btn-success').removeClass('btn-success');
  $(this).removeClass('btn-simple');
  $(this).addClass('btn-success');
})

/* Simplified version
$('.btn').click(function() {
  $(this).closest('.btns').find('.btn-success').addClass('btn-simple').removeClass('btn-success');
  $(this).removeClass('btn-simple').addClass('btn-success');
})
*/
* { outline: 0; } button { border-style: none; cursor: pointer; padding: 5px; } button::-moz-focus-inner { border: 0; }
/* Styles for buttons */

.btn-simple {
  border-bottom: 1px dashed #000;
  color: #000;
}
.btn-success {
  background-color: hsla(96, 92%, 37%, 1);
  border-radius: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btns">
  <button type="button" class="btn btn-success">Male</button>
  <button type="button" class="btn btn-link btn-simple">Female</button>
</div>
<div class="btns">
  <button type="button" class="btn btn-success">Male</button>
  <button type="button" class="btn btn-link btn-simple">Female</button>
   <button type="button" class="btn btn-link btn-simple">Third</button>
</div>

Check out the fiddle here.

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

Implementing the ability to add and remove classes in JavaScript

I am trying to implement an add or remove class feature in JavaScript, but I'm facing some issues with it. Below is the code snippet I have: if (window.location.hash == "#/profile/"){ document.getElementById("tabMenu").removeClass("bottomTa ...

The error message "firebase.initializeApp is not defined" indicates that the object is not properly initialized

Every time I try to open the debugger in Safari, I encounter an error indicating that 'undefined' is not recognized as an object when evaluating 'firebase.initializeApp'. The error specifically points to the line of code: firebase.initi ...

Trigger the click() event in jQuery before the blur() event

Looking to implement autocomplete suggestions in an input field? Take a look at the code below: <input type="text" id="myinput"> <div id="myresults"></div> To hide the results' div on the input's blur event, you can use this c ...

using a dynamic v-model as an argument in a function call

I am completely new to using vuejs and currently working on creating a dynamic table. In this table, the left column will contain hidden input fields that will be used to query a database and display the results in a pop-up window for quick referencing. ...

Looking for a way to store data in local storage so it remains even after the page is reloaded? I tried adding a local storage function, but it doesn't appear to be

I am currently working on a project involving a work day scheduler and I am facing challenges in saving data within the schedule events, like at 8am, and making sure it persists on reload. The colored time block element that changes as hours pass in the da ...

Transforming Several Dropdowns using jQuery, JSON, and PHP

Hey there! I'm looking to update the state depending on the country and city based on the chosen state. <label>Country:</label><br/> <select onchange="getval(this)"> <option value="">Select Country</op ...

How can you achieve three layers of nested quotes in Dynamic HTML?

Working on an app that utilizes JQuery and JQTouch for iOS. The issue I'm facing involves dynamically generated HTML lists where the user clicks a row that needs to be highlighted. However, achieving this has proven tricky due to nesting 3 sets of quo ...

Is there a permanent solution to fixing the error code -4094 that is repeatedly occurring during React Native startup?

When attempting to execute react-native start, an error occurred which has not been encountered before. The error message is as follows: ERROR ENCOUNTERED Loading dependency graph...events.js:287 throw er; // Unhandled 'error' event ...

Managing numerous ajax forms within a single page

Upon receiving advice from the following inquiry Multiple forms in a page - loading error messages via ajax, I am endeavoring to incorporate multiple forms within one page. The goal is to insert error messages into the corresponding input div classes. I pr ...

Interactive horizontal slideshow for hyperlinks - bootstrap framework and model-view-controller architecture

I am currently working on an MVC project that utilizes Bootstrap. My requirement is to have a horizontal menu of links that can slide left and right using arrows (similar to a carousel, but for links instead of images). To be more specific, the menu need ...

Jade: Incorporating a JavaScript file at a specific location

Is there a way to include a file that is specifically used when rendering a jade file on the client side? Here is an example of the .jade file: button(type="button")#start.flex p#timer.flex button(type="button" )#stop.flex script(src='../public/js/ti ...

Apologies, but it seems there was an issue reading the "checked" property as it is null

I am currently facing an issue with the submit button in my Django application. It appears that the Javascript function is unable to determine which checkboxes are checked, as all I see in the console logs are "cannot read properties of null, reading "chec ...

What exactly is the purpose of the colon in JavaScript's import statement?

Looking at the following example. import { QueryClientContract, TransactionClientContract } from '@ioc:Adonis/Lucid/Database' I am puzzled by the use of colons and I am unsure about where the imported files are being referenced from. ...

Utilizing divisions for specifying CSS attributes

I'm attempting to distinguish the CSS properties of two tables based on which DIV they are contained within. If you take a look at http://jsfiddle.net/jdb1991/tpXKT/, you will notice that the table in "resultA" is utilizing the TD property designated ...

Utilizing LessCss for color transparency and variable declarations with @vars

I'm attempting to create a function using LessCss, but I am encountering an issue: .transparent-border (@alpha:.15, @color:'0,0,0', @type: solid, @size:1px) { @val: @size @type rgba(@color, @alpha); border: @val; } The problem er ...

Launch target _blank within a modal instead of a new tab

I'm currently exploring ways to use vanilla JavaScript in order to display all external links - particularly those that typically open in a new tab or window - within a modal box instead. My goal is to implement a listener on external links (those no ...

Customizing the style of an element in Vue depending on the size of the window

I am struggling to update the appearance of an HTML element when the window size is below 500px. Currently, I have a computed property that sets a background-image for the element. I attempted to use an if statement within the computed property to check if ...

Navigate back to the previous page following the completion of an AJAX data submission

When using ajax to send data from page A to the server, the spring controller returns welcome page B. This process works correctly on Firefox and Internet Explorer, but on Chrome, there is an issue where after successfully sending the data via ajax, the de ...

"Organizing a menu in JSON format based on alphabetical

After following this guidance, I successfully created a JSON menu. However, the items are currently sorted by ID and I am in need of sorting them alphabetically. I am unsure about whether using array.sort(); would be applicable in this scenario. Check out ...

Is there a way to capture the stdout and stderr output from a WebAssembly module that has been generated using Emscripten in JavaScript?

In my C++ code snippet below: #include <iostream> int main() { std::cout << "Hello World!" << std::endl; return 0; } I compile the code using: emcc -s ENVIRONMENT=shell -s WASM=1 -s MODULARIZE=1 main.cpp -o main.js This c ...