The color of the button does not change when the jQuery onclick event is triggered

I am facing an issue with my buttons, specifically with Button 2. When Button 2 is clicked, I want the background color to change using an onclick event. However, despite my efforts, I have been unable to achieve this. Whenever I click Button 2, the color of Button 1 changes instead. The same issue occurs when I click Button 3.

var count = 1;
    function setColor(btn, color) {
     var btn = 'button';
     var color = '#101010';
    
        var property = document.getElementById(btn);
        if (count == 0) {
            property.style.backgroundColor = "#FFFFFF"
            count = 1;        
        }
        else {
            property.style.backgroundColor = "red"
            count = 0;
        }
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button type="button" id="button" onclick="setColor()">Button 1</button>
<button type="button" id="button" onclick="setColor()">Button 2</button>
<button type="button" id="button" onclick="setColor()">Button 3</button>

Here is my updated code:

 $.ajax({
 type: "POST",
 data: {city:city,locality:locality},
  url: "rentlocalityFilter.php",
 success:function(data){

   var htmlString='';
          $.each( res['data'], function( key, value ) {
           var id = value.id;
           htmlString +='<a class="col-md-1 icon" style="margin-top:10px;cursor:pointer" onclick="guesttt_login()"><i class="fa fa-heart" aria-hidden="true" style="margin-top: -11px; color: red;" id="button" id="button" onclick="setColor('+value.id+')"></i></a>';

        });

 }

 });


var count = 1;
function setColor() {
 var btn = 'button';
 var color = '#101010';

    var property = document.getElementById(btn);
    if (count == 0) {
        property.style.backgroundColor = "#FFFFFF"
        count = 1;        
    }
    else {
        property.style.backgroundColor = "red"
        count = 0;
    }
    }

Answer №1

It is essential for IDs on an HTML page to be unique.

To ensure uniqueness, IDs should be assigned as follows:

<button type="button" id="button1" onclick="setColor('button1')">Button 1</button>
<button type="button" id="button2" onclick="setColor('button2')">Button 2</button>
<button type="button" id="button3" onclick="setColor('button3')">Button 3</button>

Additionally, modify your JavaScript code as shown below:

var count = 1;
function setColor(_btn, color) {
 var btn = _btn;
 var color = '#101010';

    var property = document.getElementById(btn);
    if (count == 0) {
        property.style.backgroundColor = "#FFFFFF"
        count = 1;        
    }
    else {
        property.style.backgroundColor = "red"
        count = 0;
    }
}

Answer №2

Give this a try:

<button onclick="setColor(this)">Button 1</button>
<button onclick="setColor(this)">Button 2</button>
<button onclick="setColor(this)">Button 3</button>

var count = 1;
function setColor(btn) {
    var color = '#101010';
    if (count == 0) {
        btn.style.backgroundColor = "#FFFFFF";
        count = 1;        
    } else {
        btn.style.backgroundColor = "red";
        count = 0;
    }
}

Check out this example on jsfiddle

Edit 1:

The last update you made is a step in the right direction, but the solution still lacks information about the value variable. It's recommended to add an Id like this,

id="'+value.id+'" onclick="setColor('+value.id+')
, or you can use jquery for a cleaner solution.

<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>

var count = 1;
$(document).ready(function() {
  $("button").click(function() {
    var btn = $(this); 
    var color = '#101010';
    if (count == 0) {
      btn.css("backgroundColor", "#FFFFFF");
      count = 1;
    } else {
      btn.css("backgroundColor", "red");
      count = 0;
    }
  });
});

Here is a jquery solution for you to try

Hope this helps!

Answer №3

Check out this example, it's functional and has a minimal amount of code. Simply pass the clicked element to the function and use toggleClass to change the background color.
http://api.jquery.com/toggleclass/

   
    function changeColor(elem) {
     $(elem).toggleClass('active')


    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button type="button"  id="button1" onclick="changeColor(this)">Button 1</button>
<button type="button" id="button2" onclick="changeColor(this)">Button 2</button>
<button type="button" id="button3" onclick="changeColor(this)">Button 3</button>
<style>.active{background-color:red}</style>

Answer №4

To achieve this effect, follow these simple steps:

var counter = 1;
    function changeColor(btn) {

     var colorCode = '#101010';
        var buttonElement = document.getElementById(btn);
        if (counter == 0) {
            buttonElement.style.backgroundColor = "#FFFFFF"
            counter = 1;        
        }
        else {
            buttonElement.style.backgroundColor = "red"
            counter = 0;
        }
    }

Remember to include the value.id within the id attribute when calling the function

htmlString +='<a class="col-md-1 icon" style="margin-top:10px;cursor:pointer"> <i class="fa fa-heart" aria-hidden="true" style="margin-top: -11px; color: #8bc34a;" id="'+value.id+'" onclick="changeColor('+value.id+')"></i></a>'

Answer №5

Here is an example of HTML code:

<button type="button" id="button1" onclick="setColor('button1')">Button 1</button>
<button type="button" id="button2" onclick="setColor('button2')">Button 2</button>
<button type="button" id="button3" onclick="setColor('button3')">Button 3</button>

And here is an example of JavaScript code:

var count = 1;
function setColor(btnId) {

 var color = '#101010';

    if (count == 0) {
        btnId.style.backgroundColor = "#FFFFFF";
        count = 1;        
    }
    else {
        btnId.style.backgroundColor = "red";
        count = 0;
    }
}

I hope this information is helpful to you.

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

Incorporate a PHP GET parameter through an onclick event to redirect using window.location in JavaScript when a button is

I am trying to modify the onclick event of buttons that look like this: <button class="buttons" onclick="window.location='page_test.php?VAR=1&VAR2=2'">BUTTON 1</button> <button class="buttons" onclick="window.location='p ...

Angular Bootstrap div width not displaying fully on iPad device

My layout includes 2 columns in a single row, which is functioning properly on most devices. However, when viewed on an iPad, the layout does not span the full width of the screen. Here is a snippet of my code: <div class="row"> ...

Discovering the method to retrieve the values from 2 dropdown lists that are populated by a JavaScript function

I have a pair of dropdown lists in a JSP file labeled 'speciality' and 'super_speciality'. Clicking on an option in the 'speciality' dropdown list dynamically populates options in the 'super_speciality' dropdown list ...

Click on the link to return to the previous page on the website

As I work on customizing a Tumblr theme, I find myself facing a few challenges. One such issue is my desire to include a link on post pages that directs users back to the previous page, similar to what is shown in this image: picture1 I have attempted var ...

Reposition the origin when scaling SVG

Can anyone assist me in repositioning the smoke group origin to the center so that it scales along with the rocket? I've attempted utilizing the following: transform-origin: center; translate-box: box-fill; but it doesn't seem to resolve the i ...

`javascript pop up notification will only display one time`

I am currently developing a chrome extension with two different modes. When the user clicks on the icon, a pop-up message should appear to indicate which mode is active. However, I am facing an issue where the message does not always display when the pop- ...

What is the best way to display a variable (string/int) from a PHP file onto an HTML file?

I've searched online multiple times for a solution, but most of the results I found only show how to echo HTML code from a PHP file by changing the file extension to .php. However, my goal is to echo a variable from a PHP file and display it in an HTM ...

Utilize the power of XMLHttpRequest to fetch and load numerous audio files, seamlessly integrating them for playback through the Web Audio

I am looking to create a web application that loads three different audio files, each one second long, in a specific order, and then merges them into a single Audio Buffer consecutively. To illustrate my goal, here is a sample code snippet: var AudioCo ...

Discover the offsetTop value of a child element in React using TypeScript

How can I retrieve the offsetTop of React children in Typescript? Here is an example of my component: export default class FadeIn extends Component { private onScroll = () => { React.Children.forEach(this.props.children, child => { // G ...

Is it possible to dynamically update the contents of a modal body and modal footer using

I'm dealing with a modal that dynamically populates two sections: modal-body and modal-footer. However, the issue is that only the content of modal-body changes dynamically while modal-footer remains static. Here's an example of the HTML code (w ...

Tips for utilizing the @Input directive within the <router-outlet></router-outlet> component

I am new to Angular 4 and recently discovered that in Angular, data can be passed from a parent component to a child component using @Input like this: <child [dataToPass]="test"></child> My question is, how can I achieve the same functionalit ...

What is the best way to incorporate interactive columns in DataTables?

I am utilizing jquery datatables to present data. <table class="report-tbl table-bordered" cellspacing="0" width="100%" id="report-tbl"> <thead> <tr> <th></th> ...

Activate lightbox on click to swap image source temporarily

I have implemented the Materialize CSS "Material Box" lightbox plugin, but I am facing an issue. I want all the thumbnails to be uniform in size, and when clicked, the full photo should be displayed. Currently, I am using the onclick function to change th ...

Issue with [rowHovered] directive in PrimeNG Table when cell-background is defined

I am working with a scrollable TreeTable where I have defined the rowHover attribute in the following manner: <p-treeTable [value]="items" [columns]="scrollableCols" [resizableColumns]="true" [frozenColumns]="frozenCols" [scrollable]="true" scrollHeigh ...

Storing selected checkbox values in an sqlite database using JavaScript

I am working on an ejs form that includes multiple checkboxes for users to select their interests. These selections should be saved to a sqlite Database table. The table is being created with bootstrap: db.exec('CREATE TABLE interests(interest text)& ...

Changed over to a promise-oriented database, causing my login feature to malfunction completely

Although I can successfully register, when I am redirected to my game route, all I see is a blank Error page with [object Object] on the screen. This message also appears in my console periodically. Initially, I suspected an issue related to socket.io, bu ...

Occasionally, the map may take a moment to fully load

Update: Resolving the issue involved directly calling these two methods on the map object: leafletData.getMap().then(function(map) { map.invalidateSize(); map._onResize(); }); Encountering a minor yet bothersome problem with the Leaflet directive ...

Mobile phone web development using HTML5

I am currently facing an issue with playing sound on mobile browsers. In my code snippet, I have the following: Response.Write("<embed height='0' width='0' src='Ses.wav' />"); While this works perfectly fine on desktop ...

Display a section of the picture at maximum width

Can anyone help with displaying only a portion of an image at full width (100%) without any overflow issues? The code I've tried is not working: .intro_sea { position: absolute; width: 101%; clip-path: inset(30% 50% 0 0); margin: 0; paddi ...

Refreshing an HTML table with new data using jQuery and Ajax after a different selection

Currently, I have a piece of code that allows me to select two players and display some statistics about them. The data is presented using a regular table (image1). The issue I am facing is that when I select a new player, instead of updating the informat ...