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

The outcome of a MySQL query involving JSON_OBJECT() is a string value

I have crafted a query that extracts posts from a table and includes information about each post's author: SELECT post.id, post.text, post.datetime, JSON_OBJECT( 'username', user.username, 'firstName', user.firstName, 'last ...

Expanding worldwide mixin in Nuxt.js

Currently, I am working with Nuxtjs version 2.15.7 and have a mixin file structured like this: utils.js : import Vue from "vue" if (!Vue.__utils__) { Vue.__utils__ = true Vue.mixin({ data(){ return{ ... } }, ...

Interpret a JavaScript array response

Currently, I am working on an API request where I receive an HTTP response that contains an array with a single JSON object. However, when attempting to parse or stringify it using the following code: var response = http.response; try{ var json = J ...

Encountering a hitch while attempting to integrate a framework in Angular JS 1

Having experience with Angular JS 1 in my projects, I have always found it to work well. However, I recently encountered a project that uses Python and Django, with some pages incorporating Angular. The specific page I needed to work on did not have any An ...

JQuery loader & amazing animations

I have implemented the wow.js plugin along with a jQuery preload tutorial from here. Although the preloader works fine, I am facing an issue where the animation by wow.js starts before all the elements on the page are preloaded. I am looking to modify my ...

What is up with this strange JavaScript variable string / DOM selection?

I'm facing a strange issue with a variable that appears to be a string when alerted, but in the console, it is actually a DOMSelection presented in tree form. How can I retrieve the actual string value from this console output? DOMSelection anchorNod ...

AngularJS modal popup with a selectable table

Is there a way to open a modal popup containing a table in my application? I'm trying to achieve this by setting up an event in my app.js that triggers the modal when a row is clicked. Additionally, I need to update a field with the selected item&apos ...

Utilize the ::before selector to insert white spaces

I attempted this solution, but unfortunately it did not produce the desired outcome: .stackoverflow::before { font-family: 'FontAwesome'; content: "\f16c "; } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-aw ...

`Positioning of inline-block elements`

I am encountering an issue with the display CSS attributes set for three tags: a - inline-block img - block span - inline <a id="first"> <img/> <span> A first line of text B second line of text </span> </a> <a id="secon ...

"Enhance Your Online Shopping Experience with Woocommerce Ajax Filters and

I have a structure that looks like this: Company Google Apple Microsoft Material Wood Metal Plastic Essentially, Brand & Material are attributes in the Woocommerce system, while the rest are variables. I am currently working on implementing AJAX fi ...

Table Dimensions Dream Weaver

After creating a basic PHP webpage using Dream Weaver CS5 Version 11.0 Build 4964, I encountered an issue. My webpage is structured with a table containing 10 rows, each row consisting of a single cell. Within each table cell, there is a nested table tha ...

How do I create more space in Vitepress to prevent the text from feeling cramped and allow it to display in a larger area?

Below is the content of my index.md file: --- # https://vitepress.dev/reference/default-theme-home-page layout: home hero: name: "TP2" text: "Analyzing the code of TP2 by Breno Mazzali Medeiros Tomazelli and Philippe Bouchard" ta ...

The authentication method "discord" is not recognized

Currently, I am working on implementing discord authentication using passport. Originally, everything was functioning correctly, but now it seems to have encountered an issue which I cannot identify. auth.js const express = require('express') co ...

What is the best way to design a three-color column layout without any text?

I am attempting to design a three-color column layout using Bootstrap without any text. I have successfully created the columns with the desired colors, but I am facing an issue regarding how to remove the text without affecting the size of the columns. W ...

jQuery/AJAX caching problem

I have a question regarding retrieving data using $.ajax multiple times. I am facing an issue where the data is not getting refreshed with each call, instead I am receiving the same old data every time I make a call to $.ajax. Surprisingly, this code was w ...

What could be the reason for this function failing to calculate the mean of a set of data points?

I'm facing a challenge with this beginner problem. "A task for you: Calculate the average score of a class whose test scores have been graded by a teacher. Your mission is to complete the getAverage function, which receives an array of test sco ...

Save form data as a serialized post within a colorbox

I'm currently facing an issue with serializing form data from a form within color-box. While I am able to submit the form, the form data doesn't seem to be included. Below is the script I have been using in an attempt to retrieve the form data: ...

What steps can I take to properly center and repair my web page that is currently a mess

This web page I'm working on is giving me a headache. The #titlediv just won't center and the navbar keeps disappearing randomly. It seems like a big issue that I can't wrap my head around. If anyone out there can help salvage it, here' ...

How to Choose a Radio Button from a Group using Selenium WebDriver and Java

My goal is to be able to choose a specific radio button from a set of radio buttons grouped by the name attribute: <div> <input type="radio" name="exampleInputRadio" id="optionRadio1" value="1"> <input type="radio" name="exampleInpu ...

Angular2 scripts are failing to load in the web browser

Setting up my index page has been more challenging than I anticipated. Take a look at my browser: https://i.stack.imgur.com/L4b6o.png Here is the index page I'm struggling with: https://i.stack.imgur.com/Op6lG.png I am completely stumped this tim ...