The changing of colors does not function properly when clicked in JavaScript

I am having an issue with a drop-down list that offers two options: blue and green. When I select blue and click on the text input field, its background color alternates between blue and black (the default text field color). The same applies when I choose the red option. However, the code I have only functions correctly for the first and second selections. Starting from the third selection, even if I choose red, it toggles between blue and another color. Here is my HTML:

Can anyone identify what is going wrong? I suspect that my understanding of how jQuery's change function operates may be incomplete.

$('#change_color').on('change', function() {
  // Get the selected option's text value

  var colorOption = $("#change_color option:selected").text();

  // If 'Red' is chosen, change input box to red
  if (colorOption === 'Red') {
    $('.my-input').click(function(inputBox) {
      $(inputBox.target).toggleClass('red');
    });
  }

  // If 'Blue' is chosen, change input box to blue
  else {
    $('.my-input').click(function(inputBox) {
      $(inputBox.target).toggleClass('blue');
    });
  }
});
.my-input {
  background-color: black;
  width: 5%;
  font-size: 3vw;
}

.red {
  background-color: red;
  width: 5%;
  font-size: 3vw;
}

.blue {
  background-color: blue;
  width: 5%;
  font-size: 3vw;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="change_color" class="form-control box-border" placeholder="SPECIAL CHAR">
  <option selected disabled>Special Char</option>
  <option>Red</option>
  <option>Blue</option>
</select>
<input type="text" class="my-input">
<input type="text" class="my-input">
<input type="text" class="my-input">

Answer №1

Every time you use $(element).click(...), a new listener is attached to the element. This can cause listeners to stack up if done repeatedly. In your case, changing the dropdown option adds a new event instead of replacing the previous one.

An alternative approach could be:

  • Declare a global variable to store the selected color

  • Add a change event to the dropdown. When the option changes, update the global color variable

  • Assign a click event to the input elements. When clicked, set the background color to the global color variable

You can achieve this with the following code:

let backgroundColor;                                //Global var to hold color choice

$("#change_color").on("change", function() {        //When <select> changes
  backgroundColor = $(this).val();                  //Update global var
}).change();                                        //Fire this event on page-load

$(".my-input").on("click", function() {             //When input is clicked
  $(this).toggleClass(backgroundColor);             //Toggle class
});
.my-input { background-color: black; }
.blue { background-color: blue; }
.red { background-color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="change_color">
  <option>blue</option>
  <option>red</option>
</select>

<input class="my-input" />
<input class="my-input" />
<input class="my-input" />

Answer №2

Check out the Jsfiddle here

Click on $('.my-input') to trigger a click event, remove all classes, and determine which color option you have selected.

//if option chosen is red then allow change input box to red
$('.my-input').click(function(inputBox) {
  colorOption = $("#change_color option:selected").text();
  $(this).removeClass();
  colorOption === 'Red' ? $(inputBox.target).addClass('red') : $(inputBox.target).addClass('blue');
});
.my-input {
  background-color: black;
  width: 5%;
  font-size: 3vw;
}

.red {
  background-color: red;
  width: 5%;
  font-size: 3vw;
}

.blue {
  background-color: blue;
  width: 5%;
  font-size: 3vw;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="change_color" class="form-control box-border" placeholder="SPECIAL CHAR">
  <option selected disabled>Special Char</option>
  <option>Red</option>
  <option>Blue</option>
</select>
<input type="text" class="my-input">
<input type="text" class="my-input">
<input type="text" class="my-input">

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

Changing return values with Jest mocks in TypeScript

Here I am again with a very straightforward example. In summary, I require a different response from the mocked class. Below is my basic class that returns an object: class Producer { hello() { return { ...

Incorporate a comma after the second or third digit to separate currency values in JavaScript

Is there a way to add commas to currency values at the 3rd or 2nd place depending on the value itself? The desired output format is: 1000 => 1000 10000 => 10,000 210000 => 2,10,000 2010000 => 20,10,000 12010000 => 1,20,10,000 I am currentl ...

Vue-based bot for telegram web application

Hey there, I've been working on integrating a web app with my chat bot, taking advantage of the new Telegram feature. Unfortunately, after adding the site, I'm encountering an issue where clicking the button opens up an empty page. It seems that ...

Limit selection choices in select element

Similar Question: Prevent select dropdown from opening in FireFox and Opera In my HTML file, I have a select tag that I want to use to open my own table when clicked. However, the window of the Select tag also opens, which is not desirable. Is there a ...

What makes UL stand out over OL?

Similar Question: Why is it common to use <ul> for navigation instead of <ol> ? Why do designers consistently choose to use ul for menus and other elements instead of ol? ...

Implement an event listener on the final element of a webpage utilizing querySelector

I need help with a password security check feature that changes field borders to green or red based on certain conditions. Despite successfully implementing it, the JavaScript code only selects the first field (nickname) instead of the last one. I've ...

What is the best way to save high-resolution images created with HTML5 canvas?

Currently, there is a JavaScript script being used to load and manipulate images using the fabricjs library. The canvas dimensions are set to 600x350 pixels. When smaller images are uploaded onto the canvas and saved as a file on disk, everything works c ...

Storing POST Request Data in Express

I want to use a single API endpoint for both GET and POST requests. My goal is as follows: Send multiple POST requests to /api/users with data like: {'id': 2, is_valid: 'true'} Retrieve this data by fetching the same API URL later on ...

Encountering challenges while integrating Angular with a Laravel forum creation project

Currently, I am working on building a forum application that involves users, posts, and comments using Laravel. However, the next step in my project requires integrating Angular, which is new territory for me and I'm not sure where to start. I have a ...

What is the correct way to refresh v-for loops in Vue3?

Here is a brief overview of the project: We need to display an invoice card that contains details about an invoice. Users should be able to assign payments to the invoice and also remove them. These payments are stored as objects in an array. <tr class= ...

AJAX requests sent from different origins to AWS S3 may encounter CORS errors on occasion

My current objective is to access publicly available files stored in S3. The CORS configuration for my S3 setup is as follows: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> < ...

Designing a photo frame slider for a unique touch

My skills in javascript and jQuery are limited, but I am looking to create a customizable slider. While exploring options like Flexslider (), I found it challenging to meet the following specifications: Eliminate color gaps between thumbnails Enable thu ...

Tips for creating a textarea element that resembles regular text format

I am working on creating an HTML list that allows users to edit items directly on the page and navigate through them using familiar keystrokes and features found in word processing applications. I envision something similar to the functionality of To achi ...

What is the best way to position a sidebar alongside content using flexbox?

As a newcomer to web development, I recently attempted to use flexbox for the second time while working on the layout for my website. However, I encountered an issue with trying to float aside next to content. Despite my efforts, it seems to just disappear ...

If the td element contains text, add a comma (,) and wrap the text in HTML tags. If there

Currently diving into some jQuery code and have come across a few uncertainties. Here is what I've managed to put together so far: var html = ''; data.entities.forEach(function (value, index, array) { html += index !== data.entities.len ...

I am experiencing an issue where the CSS file in the wwwroot directory does not update when I make changes to the code in ASP.NET MVC

Here is a link to my CSS file: Click here for image description This is how the file looks when built (no changes): Click here for image description Occasionally, running "clean-solution" and "build-solution" fixes the issue, but it's not working no ...

Troubleshooting: Issues with the functionality of ng-include in AngularJS

Hi there, I am new to angular js and I'm attempting to integrate a simple html file into my page. Below is the code I am using: <!DOCTYPE html> <html ng-app=""> <head> </head> <body ng-controller="userController"> < ...

Guide on how to fill a jQuery DataTable with data from an XMLHttpRequest response

I have come across multiple inquiries on this topic, but none of the solutions provided have brought me close enough to resolving my issue. Hopefully, someone out there will find it simple to address. I am attempting to populate a DataTable using an XHR re ...

Using Font Awesome Icons and Bootstrap to Enhance Google Maps Info Bubble?

I'm currently working on customizing links within a Google Maps info-bubble using Bootstrap and font awesome Icons. Successfully integrated a list-group from bootstrap for my links in the info bubble, but running into issues when trying to include a ...

Tips on configuring commas in the Prettier extension within Visual Studio Code

My CSS file is causing me some trouble. I am trying to configure Prettier in VS Code so that when I write a comma, the selector I entered stays in line with the previous one. However, whenever I save the file, the selector gets moved to the next line. My ...