Tips for identifying the correct selectedIndex with multiple select elements present on one page

How can I maintain the correct selectedIndex of an HTMLSelectElement while having multiple select elements in a loop without any IDs?

I am dynamically loading forms on a webpage, each containing a select element with a list of priorities. Each priority is associated with a different color, and when selected, the same color/CSS class should be applied to the select element. Since multiple forms can be added to the page, there are multiple select elements with the same list of priorities.

The JavaScript function provided below successfully applies styling to the options but fails to apply the style to the select element once there is more than one on the page.

The issue arises from the selectedIndex always returning the index of the last element on the page.

How can this be resolved?

function ddlColoring(high, medium, low, psar)
{

    var selectArray = document.getElementsByClassName('ac-priority');

    for (var t = 0; t < selectArray.length; t++) {
        var select = selectArray[t];

        for (var i = 0; i < select.options.length; i++) {

            if (select.options[i].value === high) {
                select.options[i].className = "lbl-action-priority-high";

                if (i == select.selectedIndex) {
                    select.className = "lbl-action-priority-high ac-priority";
                }
            }
            else if (select.options[i].value === medium) {
                select.options[i].className = "lbl-action-priority-medium";
                if (i == select.selectedIndex) {
                    select.className = "lbl-action-priority-medium ac-priority";
                }
            }
            else if (select.options[i].value === low) {
                select.options[i].className = "lbl-action-priority-low";
                if (i == select.selectedIndex) {
                    select.className = "lbl-action-priority-low ac-priority";
                }
            }
            else if (select.options[i].value === psar) {
                select.options[i].className = "lbl-action-priority-psar";
                if (i == select.selectedIndex) {
                    select.className = "lbl-action-priority-psar ac-priority";
                }
            }
            else {
                select.options[i].className = "";
            }


            select.onchange = function () {

                for (var j = 0; j < select.options.length; j++) {

                    if (j == select.selectedIndex) {

                        if (select.options[j].value === high) {
                            select.className = "lbl-action-priority-high ac-priority";
                        }
                        else if (select.options[j].value === medium) {

                            select.className = "lbl-action-priority-medium ac-priority";
                        }
                        else if (select.options[j].value === low) {

                            select.className = "lbl-action-priority-low ac-priority";
                        }
                        else if (select.options[j].value === psar) {

                            select.className = "lbl-action-priority-psar ac-priority";
                        }
                        else {
                            select.className = "";
                        }
                    }
                }
            }
        }
    }
}

Answer №1

To achieve the desired styling on a select element based on a change event, you can use jQuery as shown in the code snippet below:

$('.priority-select').on('change', function() {
  var $el = $(this);
  var selectedPriority = $el.val();
  $el.attr('data-priority', selectedPriority);
});
.priority-select {
  border: 3px solid;
}

.priority-select[data-priority="high"] {
  border-color: red;
}

.priority-select[data-priority="medium"] {
  border-color: orange;
}

.priority-select[data-priority="low"] {
  border-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select class="priority-select">
  <option value="">Select a Priority</option>
  <option value="high">high</option>
  <option value="low">low</option>
  <option value="medium">medium</option>
</select>

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

Looking to display a visualization using data from a MongoDB database

I am seeking advice on the most effective way to achieve the following goal. I have been storing user activity data in MongoDB as a log, with entries similar to: { "date":"01-01-2002T08:20:30", "task":"contact-lead", "user":"username" } My objective ...

After developing a new like button feature, I noticed that upon refreshing the page, the total like count resets to zero

Imagine creating a like button that, when clicked, first checks if the user is logged in. Only users who are logged in can click the like button and have the like count increase by 1. However, every time the page is refreshed, the like count resets to 0. W ...

Utilize AJAX to accurately capture and handle error codes

Here is a snippet of code that I want to send to my server: $.ajax({ type: 'POST', url: 'post.php', data: { token: '123456', title: 'some title', url: 'http://somedomain.com', data: & ...

Retrieve the response retrieved from AJAX/jQuery and insert it into the designated form input field

When a user inputs an address into this form and clicks on the verify address button, the following script is executed: $('#verify').click(function () { var address = $('input[name=address]'); var city = $('input[name= ...

Issue with Angular drag and drop functionality arises when attempting to drop elements within an n-ary tree structure displayed using a recursive template

I am currently exploring the functionality of angular material drag and drop. Within my application, I have implemented an n-ary tree structure. Since the specific form of the tree is unknown beforehand, I have resorted to using a recursive template in or ...

Utilize jQuery to dynamically load and assign unique ids to elements within an array

I am seeking assistance with dynamically assigning unique IDs to elements in an array using JavaScript and jQuery. I am new to these languages and need some guidance. function assignIds() { var elementIds = ['name', 'lname', ' ...

What is the best way to generate a CSS design with wavy patterns?

Check out the image below to see what I am attempting to create: https://i.sstatic.net/PlroF.png Here is my current code, but I need to make it more dynamic, similar to increasing the frequency rate of a sin or cosine wave. #wave { position: relativ ...

The error message received states: "materialize-css Uncaught TypeError: Vel is not defined as

My current setup involves webpack as the bundler/loader, and I've successfully loaded materialize css (js/css). However, when attempting to use the toast feature, an error is thrown: Uncaught TypeError: Vel is not a function The library is being inc ...

A guide on creating a downward animation of an object using CSS3

I am currently working on practicing CSS 3 animation. I am facing a challenge in figuring out how to make the item fall down the page at full speed without needing the user to track it downward with the mouse, all without using javascript. Ideally, I want ...

The installation of Wordpress features two iterations of Isotope

I'm facing an issue with conflicting jQuery versions on my Wordpress site. My theme uses Isotope v1.5.25, while a plugin I have installed loads Isotope v2.0.0. This conflict is causing bugs and other issues. How can I resolve this problem and prevent ...

struggling to access the value of a hidden field by using the parent class name

My coding experience so far looks like this- <tr class="chosen"> <td id="uniqueID">ABCDE5678</td> <input type="hidden" value="000005678" id="taxCode"> <td id="fullName">Z, Y</td> </tr> In this scenario, I need to ...

Implementing autocomplete functionality using jQuery in ASP.NET with data sourced from the code-behind file

Despite the abundance of jquery autocomplete code available in this forum, I have not yet come across anything that suits my specific SharePoint/ASP.NET web page scenario. I referred to the jquery autocomplete documentation, which was helpful. However, ple ...

jQuery - Disabling or Deleting Choices in a Navigation Bar

I am trying to create a menu where the choices are mutually exclusive. This means that if one option is selected, another related option should not be available for selection. For instance, if "Low Importance" is chosen, then "High Importance" should no ...

Discovering which page the form was submitted from using xsl template

Incorporating code like <input type="hidden" value="contact-form-1" name="getpage"> into my form is something I'm interested in, as it allows me to retrieve the URL of the page from which the form was submitted. The challenge arises because the ...

How can we refine the user information based on the selection of a radio button?

How do I apply a filter to user details when selecting a radio button? Visit Plunker *I need to display only the questions of authenticated users on the list page, so I created a plunker example. If the user is authenticated or an admin, I want to filter ...

Leveraging an external Typescript function within Angular's HTML markup

I have a TypeScript utility class called myUtils.ts in the following format: export class MyUtils { static doSomething(input: string) { // perform some action } } To utilize this method in my component's HTML, I have imported the class into m ...

What is the best way to transfer information from a view to a controller in Laravel using AJAX?

I am facing an issue with sending data from the view to the controller in Laravel version 7 I am sending data from a form and ul li elements I have an array of data in JavaScript Here is my HTML code: <ul name="ali" id="singleFieldTags&q ...

Validator returns undefined when expressing invalid data

Having an issue with validation, here is the code snippet: routes.js var express = require('express'); var router = express.Router(); var hello_controller = require('../api/controllers/helloController'); var { validationRules, validat ...

Is there a way to use jQuery to enable multiple checkboxes without assigning individual IDs to each one?

I need help finding a way to efficiently select multiple checkboxes using jQuery without relying on individual ids. All of my checkboxes are organized in a consistent grouping, making it easier for me to target them collectively. To illustrate my issue, I ...

When using HTML/Bootstrap5, the ms-auto class does not correctly align items to the right in the navbar

I'm currently working on mastering bootstrap through an online tutorial, but I've hit a roadblock when it comes to right-aligning items in a navbar. I've double-checked my code against the instructor's, and it's a perfect match: &l ...