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

Display popup depending on the post's identification number

Currently, I'm in the process of integrating Sanity into my blog. Using the json object returned from a query with useState, I managed to display my posts successfully. However, I am now faced with the challenge of populating a React-Modal with the ap ...

"jQuery's .each() method is only iterating through the last element in

I am encountering an issue with this function not operating correctly... only the last Element shows the box. NOTES: <aside> is set to position: fixed; and I understand that this is not the "correct" use of <article> tags, but it helps me dist ...

Turn off drag and drop functionality and activate selection in HTML

Recently, I encountered a strange issue where selected text became draggable and droppable onto other text, causing it to concatenate. To resolve this problem, I added the following code: ondragstart="return false" onmousedown="return false" However, thi ...

When running 'npm run dev', an error occurred after the SizeLimitsPlugin emitted at 98%. The specific dependency that was

I encountered an issue while trying to incorporate Google Maps into my Laravel project and received the following error message after running npm run dev: 98% after emitting SizeLimitsPlugin ERROR Failed to compile with 1 errors 10:52:34 PM This dependen ...

Mastering the usage of AngularJS Directive controllerAs syntax with scope is key to developing

I have included my code below: // HTML <body> <h1>{{foo.name}}</h1> <my-directive></my-directive> </body> // Scripts app.directive('myDirective', function() { return { restrict: 'E', ...

A step-by-step guide on coding a slider image

<?php $query1="SELECT * FROM user_photos_offline WHERE ssmid='$ssmid' AND status='1' ORDER BY date_uploaded DESC LIMIT 0,5"; $sql=mysql_query($query1); $count=mysql_num_rows($sql); ...

What is the best way to link my PHP with MySQL in order to execute an AJAX query?

I am currently working on making this page sortable using a dropdown selection menu. At the moment, there are only two different car makes displayed and they are not sorting properly. My ultimate goal is to enable sorting by make, model, and year, but I ne ...

The Problem of Unspecified Return Type in Vue 3 Functions Using Typescript

Here is the code snippet I am working with: <template> <div> <ul v-if="list.length !== 0"> {{ list }} </ul> </div> </template> < ...

Having trouble reaching an element within a successful Ajax call

I have encountered an issue where the element is not being recognized when putting an ajax call inside another ajax call. Here is an example of the code: $.ajax({ url: 'controleFatAcoes.php', type: 'post', dataType: 'h ...

AngularJS: Issue with scope not updating across several views

Having one controller and two views presents a challenge. ClustersController angular.module('app.controllers').controller('ClustersController', [ '$scope', 'ClustersService', function($scope, ClustersService) { ...

Error occurred during download or resource does not meet image format requirements

Encountering an issue when attempting to utilize the icon specified in the Manifest: http://localhost:3000/logo192.png (Download error or invalid image resource) from the console? import React from 'react'; import Logo from '../Images/logo1 ...

Encountering the error "ReferenceError: Cannot access 'data' before initialization" during deployment on Vercel

I encountered a problem with my project after trying to implement dynamic routing. Initially, everything was working fine locally and during deployment. However, when I attempted to incorporate dynamic routing, errors started to occur. Unfortunately, I am ...

Error: The value being evaluated in document.getElementById(x).style is not an object and is not supported

Desired Outcome for my Javascript: I am working with a div that includes an "onmouseover='getPosition(x)'" attribute which can be dynamically added and removed through my javascript by clicking a specific button. The function 'getPosition() ...

Javascript: A Fun Game of Questions and Answers

When using JavaScript exclusively, I have an array consisting of four questions, four correct answers, and four incorrect answers. The use of arrays is essential to maintain order in the data. As each question is displayed, a random number is generated by ...

Is there a way to load all movies in advance when none of the tags are selected?

In my current project, I am working on a feature that involves an array of movie objects. Each movie has a name and tags assigned to it. I want to be able to display movies based on the tags selected by the user. For example, if the user selects the tag "c ...

Looking for assistance with implementing a jQuery function for an onClick event on

I've been diving into learning jquery and managed to create a basic checkbox feature with a function that allows you to set all options as read-only by checking the "None of the above" button. <html> <body> <form id="diagnos ...

Applying Bootstrap Style to an Inline Select Element: A Step-by-Step Guide

Currently working on a page layout using Thymeleaf and Bootstrap 5. I have divided the page into two parts, with this section behaving as desired: <main role="main" class="pb-3"> <br> <p>Post office ex ...

The rendering of the .Net MVC DropDownList is not displayed properly when it is first set to be hidden

Exploring the realm of .Net MVC is a new adventure for me, and I'm hoping that resolving this issue will be straightforward. In my project, there's an HTML table row that should remain hidden upon page load but become visible once a specific opt ...

Encountering a parse error when making an AJAX call using structural functions

I'm in the process of developing an API and here is my PHP function. function retrieve_schools($cn){ $schools_query = "SELECT * FROM schools"; $school_result = mysqli_query($cn, $schools_query); $response_array['form_data'][&apo ...

Depending on external software packages

Can you explain the potential risks associated with using third-party packages and npm in a broader sense? If I were to install a third-party package like semantic-ui-react using npm, is there a possibility that I may not be able to use it on my website i ...