button does not change color upon clicking

I am currently working on a project where I am using Bootstrap to change the color of a button when clicked. However, it seems like there is an issue as the button is not changing its color upon clicking.

Below is the code for my button -

<td>
     <a id="mylink" href="#"><button class="btn btn-default btn-xs">{% trans %}Allow{% endtrans %}</button></a>
</td>

Here is my JavaScript code ---

<script type="text/javascript">
$(document).ready(function() {
        if (localStorage.getItem('isClicked')) {
                $("#mylink").addClass('btn-success');
                $("#mylink").removeClass('btn-default');
        }
        $('#mylink').on('click', function() {
                $(this).addClass('btn-success');
                $(this).removeClass('btn-default');
                // setting the value upon clicking
                localStorage.setItem('isClicked', true);
        });
});

The goal is to have the button change color when clicked, and upon revisiting the page, it should check if it has been activated. Can someone please assist me in resolving this issue?

Answer №1

It seems like the issue lies right here.

$("#mylink")

This code snippet targets the element with the id="mylink", not the one with the class="mylink"

If you intend to select a class, use this instead.

$(".mylink")

For more information on CSS Selectors, refer to: w3schools

Answer №2

Initially, the mylink element serves as a class in your code.

<a href="#" class="mylink">

However, in jQuery, you are referencing an ID ($("#mylink")). Additionally, the <a> tag is a parent of the <button> tag. So, modify every occurrence of $("#mylink") to:

$(".mylink button")

This adjustment will ensure that you target the <button> tag nested within the <a> tag with the class .mylink.

For more information: http://www.w3schools.com/jquery/jquery_ref_selectors.asp

Answer №3

When using $('#someID'), you are targeting an element by its id. However, in this case, you are using classes (such as "myLink"), so the correct selector should be $(".myLink").

Furthermore, it seems like you may be overcomplicating things. Have you considered achieving your desired result solely with CSS?

If you need inspiration, here is a similar example that might help guide you: Pressed <button> CSS

Answer №4

Your code contains a few mistakes:

  1. Remember, it is jQuery, not just plain JavaScript (they are similar but not the same)
  2. You are trying to change the class of <a> elements with the class "myLink," not <button> elements
  3. You are mistakenly using a class selector (".myClassName") as an ID selector ("#myIdName")
  4. There are other things you need to consider, such as how JavaScript interacts with DOM elements. It's important to continue reading and learning.

Nevertheless, I have created a functional example for you on JSFiddle.

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

Storing and accessing formatted text in MongoDB: A comprehensive guide

I recently started working with MongoDB for my personal blog site development. I am facing an issue where the blog post, when saved as a document in the MongoDB database, loses all of its formatting and appears as a single long paragraph. I'm seeking ...

The integration of the jQuery library within the server side of a Google Apps Container Bound Script

Can the jQuery library be utilized server-side in a Google Apps Script that is Container Bound to a Doc or Sheet? If so, what steps should be taken? In a previous inquiry on Stack Overflow, I sought guidance on incorporating jQuery into a container-bound ...

jquery blur function not triggering properly

I am not very familiar with jquery and javascript. Below is the code I have written for an input text field where I want to use blur function for validation: <div class="form-row form-input-name-row"> <label> <span>Full name& ...

Is there a way to display a PHP error message while submitting the form asynchronously?

Utilizing phpMailer in combination with AJAX to send emails. The objective is to send the email and then showcase any error messages from submit.php on contact.php Currently, every submission displays "Message sent" even if it was not actually sent. Con ...

The position of a jQuery element gets reset when both the show and stop animations are used

When I use jQuery's .position() to place an element, everything works fine. But as soon as I display an animation and then cancel it with an ajax call, the position of the element resets. function displayMessage(msg) { var $messageEl = $('#u ...

Is it appropriate to include a function within a loop?

I'm curious to know if it's considered good practice to call a function inside a loop. Both of the following code snippets produce the same result, but I want to add clarity by using a function. Is this considered good practice? Thank you. Code ...

How to maintain bootstrap accordion in the open position after clicking

I am currently facing an issue with my AngularJS view. The problem is that each time a user clicks on the textbox, it automatically closes the accordion. I would like it to remain open until another accordion is opened. <div class="col-xs-7 panel-group ...

Is it possible to pass in two separate variables to an ng directive in Angular?

I've been working on developing a password validation directive, but I've encountered a few challenges. You can find the code in this jsfiddle link One issue is that when I enter information into one input box, it automatically updates the othe ...

When nodemon is executed, it encounters an "Error: Cannot find module" issue, indicating that it may be searching in the incorrect directory

I recently encountered an issue with my Node.js project that utilizes nodemon. Despite having the package installed (located in /node_modules), I am experiencing an error when trying to start my Express server with nodemon through a script in my package.js ...

How to Retrieve a Variable from the Parent Component in a Child Component using Angular (1.5) JS

I am currently working on abstracting the concept of a ticket list building into an angular application using 2 components. 1st component --> ("Smart Component") utilizes $http to fetch data and populate an array called populatedList within the parent ...

Unable to implement a function from a controller class

I'm currently attempting to organize my Express.js code, but I've hit a snag when trying to utilize a class method from the controller. Here's an example of what my code looks like: product.service.ts export class ProductService { constr ...

Unable to set the height for ul/div elements

I'm struggling to make my navbar appear when I click the "menu button". The div seems to be present in the code, but with a height of 0. Here's the relevant section of the code causing the issue. Any suggestions on how I can resolve this? var ...

Navigating to another division segment within an HTML document using the arrow keys: a guide

There are three main div boxes colored pink, red, and green.  I would like to enable movement of all segments using arrow keys. When the page is loaded, the active box will initially be in the 'pink' segment at the center. We can then navigate ...

What are the steps to perform typecasting in nodejs?

Struggling with converting string values to numbers and encountering an error. const express=require('express'); const bodyParser=require('body-parser'); const app=express(); app.use(bodyParser.urlencoded({extended:true})); app.get(&qu ...

Angular 4's Mddialog experiencing intermittent display problem

While using MDDialog in my Angular app, I've encountered a couple of issues. Whenever a user clicks on the div, flickering occurs. Additionally, if the user then clicks on one of the buttons, the afterclose event is not triggered. Can anyone provide ...

Issues with CSS and JavaScript functionality persist within the Flask framework

Having trouble with CSS and JavaScript on my website hosted via Flask framework on PythonAnywhere. Here is the directory structure: home/dubspher/mysite/ - README.md - app.py - index.html Static/ - css - fonts - images - js - sass Original HTM ...

"Webpack error: Including a comma within a string leads to a syntax problem when bund

I'm attempting to merge this file into my main JS. var constants = { height: 600, width: 400, default_bezier = "[ { \"startPoint\" : [51.6503017608354,203.464445873753], \"endPoint\" : [-52.41285540263849,202.372456432 ...

Exploring the ID search feature in JavaScript

I'm facing an issue with implementing a search feature in my project. Here is the HTML snippet: HTML: <input type="text" id="search"> <video src="smth.mp4" id="firstvid"> <video src="smth2.m ...

Ensuring the text remains positioned above another element constantly

Looking to have the text float above a regular box and resize the font size accordingly? Here's what I've tried: https://jsfiddle.net/a87uo3t2/ @import url('https://fonts.googleapis.com/css?family=Share+Tech+Mono'); body { margin: ...

Is receiving shelter from a different aspect, Cypress

Encountered a timeout error while attempting to select an element with cy.select(). The following element: <select aria-describedby="searchDropdownDescription" class="nav-search-dropdown searchSelect" data-nav-digest="Xa0GQ+pPQ/ ...