A plethora of color choices in a Multi-select Box

Hi there! I am facing an issue with dynamically adding multiple select boxes.

Currently, I have 4 color-coded options under the selection boxes, which work fine when there is only one box. However, when I add more than one select box, the color coding doesn't seem to work properly. Can anyone help me with this problem?

You can find the sample code in this JSFiddle link.

Below is the HTML code snippet:

    <tr>
    <td class="tg-7khl">MAV_01</td>
    <td class="tg-7khl">Maveric Poster</td>
    <td class="tg-7khl">Maveric</td>
    <td class="tg-7khl">PRE,VIN,MUK</td>
    <td class="tg-7khl">14 Aug 2015</td>
    <td class="tg-7khl">
        <select id="stat" class="redText" style="padding: 3px; display:block;">
            <option class="redText">Yet to start</option>
            <option class="orangeText">In Progress</option>
            <option class="blueText">Waiting</option>
            <option class="greenText">To invoice</option>
        </select>
    </td>
    <td class="tg-7khl red">from 12 Aug 2015</td>
</tr>

Answer №1

There are a couple of issues that need to be addressed in the code.

1) The select element IDs are duplicated, which is not allowed as IDs must be unique. It would be better to use the same class name and target elements by classname instead.

2) Instead of using the object of get elements in the click handler, it is recommended to use the current element context this in the handler.

Here is the full snippet:

var selectele = document.getElementsByClassName('stat');
  for(var i=0;i<selectele.length;i++)
    selectele[i].onchange = function () {
      this.className = this.options[this.selectedIndex].className;
    }
}

Check out the working demo here

Answer №2

Make sure to check out this updated JSFiddle for a working solution. The previous code had issues with duplicating IDs, but you can also achieve the desired functionality by using classes.

var select = document.getElementById('stat');
select.onchange = function () {
    select.className = this.options[this.selectedIndex].className;
}
var select1 = document.getElementById('stat1');
select1.onchange = function () {
    select1.className = this.options[this.selectedIndex].className;
}
var select2 = document.getElementById('stat2');
select2.onchange = function () {
    select2.className = this.options[this.selectedIndex].className;
}

Answer №3

Each element should have a unique identifier called <code>id
. Instead of using id, it is recommended to use the class redText like shown below.

var select = document.getElementsByClassName('redText');

for (var i = 0; i < select.length; i++) {
    select[i].onchange = function () {
        this.className = this.options[this.selectedIndex].className;
    }
}

Check out the DEMO here

Answer №4

Using the same id for multiple elements can lead to issues when trying to retrieve all elements by id.

To fix this, consider changing all ids to classes like so:

<select class="stat redText" style="padding: 3px; display:block;">

Instead of using this.className, use the following code snippet to only target the current select box where the value has changed:

var select = document.getElementsByClassName('stat');
for(var i = 0; i < select.length; i++) {
  select[i].onchange = function () {
    this.className = this.options[this.selectedIndex].className;
  }
}

Check out the JSFiddle Demo for reference.

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

Utilize the RRule library in JavaScript by incorporating the rrule.min.js script

I am having trouble integrating the library https://github.com/jakubroztocil/rrule into my website. Whenever I try to do so, I encounter the error: Uncaught SyntaxError: Unexpected token { I have attempted the following: <!DOCTYPE html> <html ...

The term "GAPI" has not been declared or defined within the Svelte

Encountering an issue while trying to incorporate the Youtube data API into my Svelte application. Upon loading the site, the error message displayed is: Uncaught ReferenceError: gapi is not defined Reviewing the relevant code reveals: <svelte:head> ...

Determining When the Collapse Transition in Material UI 5 is Complete

Snippet <Collapse in={expanded} onTransitionEnd={() => console.log('finished')} > <div>foo</div> </Collapse> Error Detection The callback function (onTransitionEnd) is not triggered af ...

After implementing rewrites, my dynamic routes in Next.js are no longer functioning as expected

This is the current structure of my project and it was working fine before I added rewrites to my project. https://i.sstatic.net/X989W.png -dashboard --admin --page.tsx ---[adminId] ---page.tsx --cars --page.tsx ---[carId] ---page.tsx -lo ...

JavaScript Question: How can I extract the click value from a JavaScript visualization when displayed in a table?

I am working with a Hierarchical Edge Bundling visualization in JS. My goal is to have the name of the value displayed on the table when I click on it. Currently, I am facing an issue with retrieving the value dynamically. If I manually input a value, I c ...

Ever since updating my Node JS, the functionality of the MaterializeCSS carousel methods has ceased to work

Recently, I encountered some issues with my React project that features a materialize-css carousel. The problem arose after updating my nodeJS version from 14.8.1 to 16.13.0. Specifically, these errors kept popping up: TypeError: Cannot read properties o ...

Why do my tablet media queries take precedence over mobile view media queries?

I've noticed that when I view my website on mobile devices, the tablet media queries always seem to override my mobile media queries. Can anyone explain why this is happening? Here is how I have set it up: /* X-Small devices (portrait phones, less t ...

PHP and XML encountered a parsing error: unexpected occurrence of the T_OBJECT_OPERATOR

I've been troubleshooting a PHP page that reads data from an XML file. I keep running into this error message: Parse error: parse error, unexpected T_OBJECT_OPERATOR on line 24. I'm unsure of the cause of the error and need help figuring out what ...

Struggling to get my upload form to function properly with two different versions of jQuery, even after attempting to use jQuery.noConflict

I am facing an issue with a webpage that contains two different forms. The first form is for uploading pictures and generating the link for the uploaded images, while the second form is a regular one used to add products to a database using the links from ...

Utilizing Browserify routes and configuring Webstorm

When building my project using gulp and browserify, I made use of path resolution for easier navigation. By following this guide, I configured browserify as shown below: var b = browserify('./app', {paths: ['./node_modules','./src ...

Is it possible to achieve 100% screen height by combining a fixed height div with a stretchy height div?

I have a design concept that I'm trying to bring to life. I'm struggling with figuring out how to add another "stretchy div" to the layout. I want this second div to expand to fill all remaining vertical space on the screen without causing it to ...

Angular 2 module transpilation services

In my angular 2 application, there is a module called common. Here is how the project structure looks like: main --app /common --config //.ts configs for modules --services //angular services --models --store //ngrx store /co ...

Creating Json for jsTree can be done by following these steps

Yesterday, I stumbled upon the versatile jsTree plugin and was really impressed. Does anyone happen to have a SQL sample that creates JSON data for it? ...

Ways to Read JSON without Using jQuery

Exploring JSON Feed and Autocomplete As I delve into the realm of creating an autocomplete feature that fetches data from a JSON feed, I encounter a setback. Despite successfully parsing the JSON data using json2.js through JSON.parse, I am confronted wit ...

Utilize the serialized data to pre-fill the form fields

After using the serialize() function on my form and saving the string, I am now looking for a function that can repopulate values back into the form from the serialized string. Is there such a function available? ...

Tips for emphasizing specific sections of text in CodeMirror utilizing substring positions

I am currently utilizing CodeMirror () as a text editor with additional functionalities. One of these features includes highlighting specific words or groups of words based on their positions within the original string. I have an external structure that st ...

How to address critical vulnerabilities found in a Vue.js project that relies on the 'vue-svg-loader' dependency, specifically impacting 'nth-check', 'css-select', and 'svgo'?

Attempting to launch a Vue version 2 project, encountered the following error: # npm audit report nth-check <2.0.1 Severity: high Inefficient Regular Expression Complexity in nth-check - https://github.com/advisories/GHSA-rp65-9cf3-cjxr fix available ...

Managing numerous asynchronous calls using jQuery

I am facing an issue with the tab structure on my website. When clicking on each tab, an AJAX call is made to a unique URL. However, when I click on consecutive tabs, the AJAX call results in an error instead of success. Only the tab that is loaded ini ...

How can I adjust the size of my elements to be responsive in pixels

While browsing through Quora and Facebook feeds, I noticed the fixed size of user display pictures: width: 40px; height: 40px; Even when resizing the browser window for a responsive design, these pictures maintain their size at 40px x 40px. What other f ...

Designing a dynamic patterned backdrop that seamlessly extends for a column in bootstrap

Experiencing some difficulties with Bootstrap and creating a resizable column background. In one row, there is a column with a fluid image at the top, another column below it with a CSS class that gives it a repeating background along the Y axis, and fina ...