Adjust the button's color even after it has been clicked

My goal is to update the button's color when it's clicked. I found some examples that helped me achieve this, but there's an issue - once I click anywhere outside of the button, the CSS class is removed. These buttons are part of a form, and I want them to maintain the active state CSS until the form is submitted.

This is what I've done so far:

jQuery('.choose-school').click(function() {
  jQuery(this).toggleClass('active');
  if (jQuery(this).hasClass('active')) {
    jQuery(this).text('SELECTED');
  } else {
    jQuery(this).text('SELECT');
  }
});
.choose-school.active {
  background-color: #eeffd4;
}
.choose-school:active {
  background-color: #eeffd4;
}
.choose-school:focus {
  background-color: #eeffd4;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button type="button" class="choose-school">
  <h3>Testing
    <span class="select-active">SELECT</span>
</button>

I attempted using :active and :focus to address the issue, but it didn't work. Additionally, in the JQuery code, I'm trying to change the text of the span from "SELECT" to "SELECTED." Can anyone identify what's wrong with that part of the code?

Answer №1

It is recommended to utilize $.html() rather than $.text(). This way, only the text will be retained without any tags.

An efficient method is to extract the HTML as a string, perform the replacement, and then update it. Check out the example below:

jQuery('.choose-school').click(function() {
  jQuery(this).toggleClass('active');
  if (jQuery(this).hasClass('active')) {
    jQuery(this).html(jQuery(this).html().replace('SELECT', 'SELECTED'));
  } else {
    jQuery(this).html(jQuery(this).html().replace('SELECTED', 'SELECT'));
  }
});
.choose-school.active {
  background-color: #eeffd4;
}
.choose-school:active {
  background-color: #eeffd4;
}
.choose-school:focus {
  background-color: #eeffd4;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button type="button" class="choose-school">
  <h3>Testing
    <span class="select-active">SELECT</span>
  </h3>
</button>

A more effective approach is to update the text inside the span element:

jQuery('.choose-school').click(function() {
  jQuery(this).toggleClass('active');
  if (jQuery(this).hasClass('active')) {
    jQuery(this).find('.select-active').html('SELECTED');
  } else {
    jQuery(this).find('.select-active').html('SELECT');
  }
});
.choose-school.active {
  background-color: #eeffd4;
}
.choose-school:active {
  background-color: #eeffd4;
}
.choose-school:focus {
  background-color: #eeffd4;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button type="button" class="choose-school">
  <h3>Testing
    <span class="select-active">SELECT</span>
  </h3>
</button>

Answer №2

There are a couple of issues with the code you provided:

The HTML <h3> tag was left unclosed

<h3>Testing</h3>

You attempted to change the text for the entire button instead of just the text inside

This will only modify the content within the span:

$(this).find('.select-active').text('SELECTED');

(semantical) You can use $ instead of jQuery

$(this) // ...

Here is a fixed version of your code in this fiddle: https://jsfiddle.net/fyha5m9g/

Answer №3

If you want to change the appearance of a button when clicked, it's recommended to create a new class in your CSS file and apply it dynamically using jQuery. Avoid using focus on the button as it may not be necessary in this case. Here is an example:

<script>
jQuery('.choose-school').click(function(){

        if(jQuery(this).hasClass('active')){
          jQuery(this).removeClass('active');
          jQuery(this).text('SELECTED');
        }else{
          jQuery(this).addClass('active');
          jQuery(this).text('SELECT');
        }
    });
</script>

CSS file

.choose-school.active {
    background-color: #eeffd4; 
}

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

Guide on sending an ajax request following a successful submission of a form using Contact Form 7, all while incorporating multiple tabs within Bootstrap 5

I have a scenario where I am utilizing multiple Contact Form 7 Forms within Bootstrap 5 tab panels. My goal is to trigger an Ajax request to send data after each successful form submission. To achieve this, I implemented the use of wpcf7mailsent event list ...

How can I place this ribbon on top of an image in an HTML email to ensure it displays correctly on email clients such as Outlook?

As I delve into my research, it's becoming apparent that achieving this result might not be feasible across all email clients. However, I'm curious to know if there have been any recent developments in the email world that would allow me to repli ...

Displaying incorrect text format on a TextView using Html.fromHtml()

Within my application, there is a string that represents a mathematical expression: String s = "log<small><sub>(log<small><sub>(log<small><sub>3<small><sup>2</sup></small></sub></small&g ...

HTMLElement addition assignment failing due to whitespace issues

My current challenge involves adding letters to a HTMLElement one by one, but I'm noticing that whitespace disappears in the process. Here's an example: let s = "f o o b a r"; let e = document.createElement('span'); for (let i ...

Using headers in the fetch api results in a 405 Method Not Allowed error

I am facing an issue while attempting to make an ajax request using fetch. The response I receive is a 405 (Method Not Allowed) error. Here is how I am trying to execute it: fetch(url, { method: 'get', headers: { 'Game-Toke ...

Utilizing Vue3's draggable component to seamlessly incorporate items

My current project involves the use of the vue draggable package, and below you will find the complete component: <template> <div> <button class="btn btn-secondary button" @click="add">Add</button> ...

Developing a vue.js component library without the need for constant rebuilding after every edit

Introduction: I have created two projects using vue-cli ~4.2.0: parent-app - the main project dummylib - a library that is imported by parent-app. It contains several .vue components. Currently, parent-app functions well in dev mode with dummylib being ...

What's the best way to ensure my website's footer spans the entire width of the webpage?

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Elena Brown | Graphic Designer</title> <link rel="stylesheet" href="CSS/normalize.css"> <link href=' ...

jQuery does not support PHP code recognition

I'm facing an issue with a function that gets called when I click a button. The data I pass to this function is not wrapped in a form tag, so I am manually including the csrf token: function NewDeleteBox(box_id, batch_id, staff_id){ $.ajax({ ...

Identifying the length of a division element following its addition

I'm facing difficulties in detecting the length and index of the dynamically appended div. I have researched extensively and found a solution involving MutationObservers, but I am unsure if it is necessary for this particular issue. Let's focus ...

Performing an asynchronous POST request in JavaScript

Hey there, I successfully managed to implement a post request using ajax for my submit functionality. However, I am now looking to make this asynchronous to account for any delays in processing by my php file. Unfortunately, I am struggling to figure out h ...

What is the most efficient method for updating URLs in CSS files before the website goes live?

The project I am currently working on has been worked on by various coders with different backgrounds. One of my recent achievements was writing a clean Capistrano recipe to minimize CSS and JS files. Now, the challenge ahead is figuring out how to identif ...

What is the best way to remove any objects in this array that have empty strings as values?

I have been developing a form using Angular 14. The form consists of a primary section, which includes the user's necessary information, and a secondary section where users can input additional data (an array of residences displayed in a table) befor ...

Changing the position of the checkbox label to be above the checkbox

Can you help me with rearranging the checkbox label position to be above the checkbox instead of on the left side? I currently have the labels appearing on the left-hand side of the checkboxes, but I would like them to be positioned above the checkboxes. ...

What is the best way to trigger an API call using AJAX whenever the page loads and at regular intervals using `setInterval()` function?

New to coding and seeking guidance: I have a basic AJAX feature in my project that triggers a GET API request every 3 seconds: <script> $(document).ready( function() { setInterval(function() { $.get(&apos ...

Is there a way to efficiently manage multiple modules in AngularJS? I've put in a lot of effort, but while one module is functioning properly, the

angular .module('ApplicationOne',[]) .controller('myControllerOne', function($scope){ $scope.name = "Luther"; $scope.fname = "Martin"; $scope.ed = "B.TECH"; }); angular .module('App2&apos ...

Convert HTML Form to PDF or Docx with Angular 4

My current setup involves Angular 4 with Node and MySQL. I have a form that, upon submission, needs to trigger a Save As... dialog box for the user to save the entered form contents as either a PDF or Word Doc. I've attempted using htmlDox and saveAs ...

Making a dropdown menu spin using Jquery and Javascript

I am in need of a unique solution for a dropdown menu that appears rotated 90 degrees anticlockwise. The goal is to have the dropdown select "button" text displayed vertically, with the options sliding out in a similarly rotated, sideways manner featuring ...

The dropdown item in Tailwindcss is unexpectedly flying off the edge of the screen rather than appearing directly under the dropdown button

Currently, I am developing an application using Rails, Vue, and TailwindCss 1.0+ I am facing an issue while creating a dropdown menu for my products. When I click on the dropdown button, the items in the dropdown fly off to the edge of the screen instead ...

Using jQuery to send JSON data through AJAX to PHP

I'm attempting to utilize jQuery AJAX to send JSON data to a PHP file. My goal is to extract the values and IDs from multiple child elements, create a JSON object with this data, and then transmit that object to a PHP file for processing and insertion ...