You can utilize the Toggle Button to alternate between multiple classes, not just two

Currently, I am learning Java with Spring Boot and Thymeleaf. While creating some views, I faced a challenge. Initially, I wanted to create a toggle button for "Pending" and "Received". However, now I am attempting to add the option "Cancelled", but I have encountered some issues.

<div class="row mb-3">
            <label for="statusCodes" class="col-sm-2 col-form-label"
              >Status</label
            >
            <div class="col-sm-2">
              <button
                type="button"
                id="toggleButton"
                class="btn btn-toggle btn-pendente"
                data-value="PENDENTE"
              >
                Pending
              </button>
              <input
                type="hidden"
                name="statusCodes"
                id="statusCodes"
                value="PENDENTE"
              />
            </div>
          </div>

This div was functioning correctly before.

 $(function () {
    $("#toggleButton").on("click", function () {
      $(this).toggleClass("btn-pendente btn-recebido btn-cancelado");
      if ($(this).hasClass("btn-pendente")) {
        $(this).text("Pending");
        $("#statusCodes").val("PENDING");
      } else if ($(this).hasClass("btn-recebido")) {
        $(this).text("Received");
        $("#statusCodes").val("RECEIVED");
      } else if ($(this).hasClass("btn-cancelado")) {
        $(this).text("Cancelled");
        $("#statusCodes").val("CANCELLED");
      }
    });
  });

I thought adding another class to the button would be simple, but when I did so, clicking on the "Pending" button changed the style to "Received" instead of "Cancelled."

.btn-pendente {
  width: 140px;
  color: orange !important;
  background-color: transparent;
  border: 2px solid orange !important;
}

.btn-recebido {
  width: 140px;
  color: #28a745;
  background-color: transparent;
  border: 2px solid #28a745;
}

.btn-cancelado {
  width: 140px;
  color: red;
  background-color: transparent;
  border: 2px solid red;
}

This marks my first question here, please forgive any mistakes ;)

Answer №1

You may give this a shot, it's likely to function

$(function () {
      $("#toggleButton").on("click", function () {
        if ($(this).hasClass("btn-pendente")) {
          $(this).removeClass("btn-pendente")
          $(this).addClass("btn-recebido")
          $(this).text("Recebido");
          $("#statusCodes").val("RECEBIDO");
        } else if ($(this).hasClass("btn-recebido")) {
          $(this).removeClass("btn-recebido")
          $(this).addClass("btn-cancelado")
          $(this).text("Cancelado");
          $("#statusCodes").val("CANCELADO");
        } else if ($(this).hasClass("btn-cancelado")) {
          $(this).removeClass("btn-cancelado")
          $(this).addClass("btn-pendente")
          $(this).text("Pendente");
          $("#statusCodes").val("PENDENTE");
        }
      });
    });

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

Encountering a type mismatch error in Typescript while working with Redux state in a store file

It appears that I have correctly identified all the types, but could there be a different type of Reducer missing? 'IinitialAssetsState' is not assignable to type 'Reducer' The complete error message: Type '(state: { assets: n ...

Using an array as the source for your Mui Autocomplete instead of JSON

I'm attempting to recreate the autocomplete MUI example shown here, but with a slight variation. Instead of utilizing a JSON data structure, I am simply passing an Array. Here is what I have tried: export default function SearchTutorialArray() { con ...

Are there any built-in methods in JQuery specifically designed to identify validatable elements?

Is there a way to identify and validate all the different types of form elements in a form? My attempt is not working as expected. Here is my code: var FormValidator = function (form) { this.form = form, this.elements = this.form.find(' ...

The button designed to execute JavaScript and modify CSS is malfunctioning

I am trying to use a button to expand my sidenav by toggling the class with JQuery. Although I am more familiar with JavaScript, I attempted to solve it with JS before moving to JQuery. function toggleMenu() { var sideEle = document.getElementByI ...

Creating an SVG element that adjusts to the size of its parent container: tips and tricks

I'm attempting to achieve the following: Displaying an SVG square (with a 1:1 aspect ratio) inside a div element. When the width of the div is greater than its height, the square should adjust to fit within the container based on the height (red box ...

Custom CSS styles for purchasing stocks using percentages

Can someone assist me in fixing the CSS for this custom card within a modal box? <!--Card--> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <input type="text" id="market-searc ...

Can someone help me with combining these two HTML and JavaScript files?

I successfully created an HTML/JavaScript file that functions properly: <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor ...

What is the correct way to utilize "data:" in a jQuery AJAX call?

There seems to be an issue with my code within the deletePost function. The problem lies in the fact that $_GET['title'] is empty. Although I set the title value in the ajax using postTitle: $(this).siblings("h3.blog").text(), it doesn't see ...

Using Variables Along a Chain of Promises

In my development project, I am utilizing nodejs in conjunction with the express framework and mongodb/mongoose for data storage purposes. Within my code, there exists a register function that performs four essential tasks. It creates a new user, generate ...

Navigating through complex immutable entities

I am having trouble working with multidimensional immutable arrays. I would like to make my array immutable, but I'm not sure how to do so. Consider the following data structure: // data { // item { name: someName, todos: [ ...

Is this the proper formatting for JavaScript code?

Having trouble changing the CSS of elements that match b-video > p with an embed element using JQuery. Here's my code: $('div.b-video > p').has('embed').attr('style','display:block;'); Can anyone help me ...

The React client is unable to establish a connection with the server socket

Recently diving into the world of socket-io and react, utilizing express for the backend. The socket.io-client version being used is 3.0.3, while the backend's socket-io package matches at 3.0.3 as well. Interestingly enough, the server handles connec ...

Combine Angular variable in JavaScript function

I want to combine "proposal.id" in the initial parameter of the window.open function. Here is my current code snippet: <button ion-button color="light" onclick="window.open('https://mywebsite.com/offer?id={{ proposal.id }}', '_self' ...

Preventing select from opening when closing chip in Vuetify: A simple guide

Looking at this specific situation on vuetify.com https://codepen.io/anon/pen/RqoxXY?&editors=101 Regarding the autocomplete feature with chips, is there a way to prevent the select menu from opening when I cancel a chip? I attempted using @click.st ...

"Troubleshooting: Issue with AngularJS ng-click Functionality Not Working on Re

Having trouble with the ng-click function in AngularJS when using the following HTML code: <tr ng-repeat="ai in alert_instances" ng-click="go('/alert_instance/{{ai.alert_instancne_id}}')"> <td>{{ai.name}}</td> <td>{{a ...

Top tips for writing JavaScript that incorporates an AJAX call to determine whether the default action should be blocked

Utilizing JavaScript and jQuery, I am developing a handler for form submission that will either allow or prevent the form from being submitted based on certain conditions. Although this task is fairly straightforward, it becomes more complex due to the ne ...

Best Placement for Socket.io Server in WebStorm Express Template

Trying to integrate socket.io into an express server generated by WebStorm. Should the setup of the server and socket.on events all be placed inside /bin/www, or is it better practice to create separate controllers like index and users pages? https://i.ss ...

Exploring the concept of jQuery handler functions

Within my code, I have the following: <script type="text/javascript"> $(document).ready(function (e) { $('#EventCreate').click(function (e) { location.href = '@Url.Action("Create", "AEvents")'; }); ...

Extract the property value and save it as an array in Vue

Looking to extract all values of a specific property and save them as an array. I attempted the following method: data() { return { roomList: null } }, methods: { getRooms() { var that = this axios.get('http://local ...

Is it possible to consolidate geometry in each frame during the rendering process using three.js?

Having recently delved into three.js, I've been experimenting with some concepts. My current challenge involves creating a line in the scene and using it as a reference for cloning and transforming. The goal is to display the cloned lines in a sequent ...