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

Send the id of the chosen row to the Component tag within the blade file

I'm working on passing the id of the currently selected row within a for loop when it's clicked on. The goal is to then pass that id to a Vue component. In my index.blade file: @foreach($cats as $cat) <tr> <td class="catme" d ...

Tips for Implementing a "Please Hold On" Progress Bar in ASP.NET

I have a master page named siteMaster.master, an aspx page called submission.aspx, and a user control named attachment.ascx. The script manager is included in my master page. The submission page inherits the master page and registers the user control attac ...

What is the best way to incorporate multiple conditions within a React component?

When working in React, I have the ability to conditionally render any div using the following code snippet: {hasContent && <span>{value}</span> } Recently, I attempted to include two conditions as follows: {hasContent || hasDesc &am ...

Breaking the border between columns in CSS columns

To see a demonstration of my question, please check out this fiddle. In short, I am seeking a solution for making the purple border extend to the height of the green border, overlapping it. I am open to any creative solutions and hacks. Specifically, wit ...

Does adding the async attribute to a script impact the timing of the onload event?

I am facing an issue with a webpage that contains a script tag in the HEAD section: <script src="somescript.js" type="text/javascript" async></script> Since it has the async attribute, this script loads asynchronously, allowing the browser to ...

What steps should I take to set up my React project in order to eliminate .html extensions from the html files within the public

Currently, I am tackling a project that involves integrating a React app with a static website. Simply converting the HTML to JSX is not feasible because the website utilizes custom CSS that React cannot easily render without significant refactoring. I ha ...

Continue executing without stopping

After making 4 ajax calls, the script is supposed to halt if record number 123456 is found. However, this specific record may appear in all four ajax responses. Despite this expectation, the code fails to stop processing. var endPoint0 = ''; var ...

Customize the font color in Material UI to make it uniquely yours

How can I customize the default Text Color in my Material UI Theme? Using primary, secondary, and error settings are effective const styles = { a: 'red', b: 'green', ... }; createMuiTheme({ palette: { primary: { ...

Utilizing material-ui's LocalizationProvider to display times in a different time zone

My application requires material-ui date and time pickers to function based on a remote time zone specified by the server. I want the today circle on the date picker to accurately reflect today in the remote time zone, and I need to convert the datetimes i ...

Enhance the background property in createMuiTheme of Material-UI by incorporating additional properties using Typescript

I've been attempting to include a new property within createMuiTheme, but Typescript is not allowing me to do so. I followed the instructions provided here: https://next.material-ui.com/guides/typescript/#customization-of-theme I created a .ts file ...

Conduct a unit test to verify that a function successfully connects to an API and accurately stores the retrieved data in a variable

Currently, I am working on creating a unit test for my writing and JavaScript code. This area is still challenging for me, so I am in the process of learning how to do it correctly. The specific function I am focusing on makes an API call and then assigns ...

What is the process for incorporating a personalized SVG file into the material-ui Icon Component?

For my project, I have a requirement to use custom svg files. To achieve this, I am utilizing <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0865697c6d7a616964257d61483b2631263b">[email protected]</a>. I reviewed ...

Guide for dynamically populating Jqgrid Dropdown depending on another dropdown's data选择如何根

On my screen, I have two dropdowns. One is a standard Razor dropdown and the other is a Jqgrid dropdown. The code for the Razor dropdown looks like this: <div class="col-md-4"> <label for="" class="control-label">Loan Currency</ ...

Returning Props in Dynamic Components with Vue 3

Exploring the capabilities of Vue3's Dynamic Component <component>, I am currently working with this setup: Component 1: <template> <div> <h1> Name Input: </h2> <Input :model="props.name" /> ...

Ways to attribute a numeric worth to a choice in a JavaScript form

I am in the process of creating a form that allows users to customize and order pizza while showing them the invoice as they make their selections. Currently, I have successfully implemented the display of user-selected options, but I am struggling with a ...

Use jQuery's .each method to reiterate through only the initial 5 elements

Is there a way to loop through just the initial 5 elements using jQuery's each method? $(".kltat").each(function() { // Restrict this to only the first five elements of the .kltat class } ...

Tooltip remains visible even after formatting in highcharts

I have successfully hidden the datalabels with 0 values by formatting them. However, after formatting the tooltips for 0 valued data in a pie chart, there is an issue where hovering over the 0 valued portion shows a white box as shown in the picture. I hav ...

How do I specify the default checked value for a checkbox in Redux Form?

Within our Redux Form 5.3 application (not version 6.x), the goal is to display an <input type="checkbox" /> in this manner: // Sometimes, fieldHelper.checked starts off as undefined. When a checkbox is // clicked by the user, fieldHelper.checked is ...

Utilizing HTML injection to access both the Chrome API and global variables

I am currently developing a new Chrome Extension and am diving into the process for the first time. My extension involves injecting an HTML sidebar into web pages, adding JavaScript functions to the header, and allowing users to interact with buttons on th ...

Blue outlined React Select dropdown with search functionality

When the dropdown is searchable, there seems to be a blue outline around the cursor: Link to image To remove the cursor, you can use this CSS: .Select-input > input { color: transparent; } Is there a way to also eliminate the blue outline on f ...