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

What is the best way to eliminate borders on a span element so they collapse seamlessly?

When using the tryit editor on this html and narrowing the result window (to around 200px), the border ends up inside the span as it spans across multiple lines. Is there a way to make the border "collapse" so that it forms a single irregular border around ...

Tips for starting the debugging process with POST and GET requests in Django and the Python Shell

I've encountered an issue with my code where the database is not updating and a new record is not being created. I suspect that there may be a problem with how I am handling the POST data retrieval in my script. Can anyone provide guidance on where to ...

Drag a spinning cube using CSS and Jquery when the mouse is pressed

I'm attempting to develop a dynamic rotating cube that users can manipulate to their desired side by clicking and dragging on the cube. Currently, I have functionality where the cube moves as the mouse cursor moves across the screen, but this results ...

Add the file retrieved from Firestore to an array using JavaScript

Trying to push an array retrieved from firestore, but encountering issues where the array appears undefined. Here is the code snippet in question: const temp = []; const reference = firestore.collection("users").doc(user?.uid); firestore .collec ...

Actions cannot be performed on elements generated by ng-repeat

I am facing a challenge where I need to display a list of languages on a page, allowing users to change their selections based on previous choices. To achieve this functionality, I have written the following code snippet: ... <tbody> & ...

Adjust the aesthetic based on whether the field is populated or empty

I have a simple text field on my website that triggers a search when the user inputs a value. I am wondering if it is possible to style the text field differently depending on whether it is empty or has content. Specifically, I want to change the border c ...

Displaying text and concealing image when hovering over a column in an angular2 table

I am currently using a table to showcase a series of items for my data. Each data entry includes an action column with images. I would like to implement a feature where hovering over an image hides the image and reveals text, and vice versa (showing the im ...

Generate a new entry by analyzing components from a separate array in a single line

I have a list of essential items and I aim to generate a record based on the elements within that list. Each item in the required list will correspond to an empty array in the exist record. Essentially, I am looking to condense the following code into one ...

re-establishing multiple selections in a dropdown menu in PHP/HTML

Hey, I've got this multi-select listbox... <select id="extfeat" name="extfeat[]" size="6" multiple=""> <option value="Wheel_Chair Accessible">Wheel Chair Accessible</option> <option value="Fruit_Trees">Fruit Trees& ...

Tips for extracting data from an Angular object using the *ngFor directive

https://i.stack.imgur.com/ai7g1.png The JSON structure displayed in the image above is what I am working with. My goal is to extract the value associated with the key name. This is the approach I have taken so far: <span *ngFor="let outlet of pr ...

Filtering dynamically generated table rows using Jquery

I'm currently working on a project that involves filtering a dynamic table based on user input in a search bar. The table contains information such as name, surname, phone, and address of users. Using jQuery, I have created a form that dynamically ad ...

When attempting to use jQuery to click on a button that triggers an ajax callback, the functionality does not

I am facing an issue with my Drupal website. I have created a form with a button that has an ajax callback. The callback works perfectly, but now I want to execute a small JavaScript function when the user clicks on the submit button. Instead of creating ...

Is it possible to generate unique identifiers for v-for keys using vue-uuid?

I'm attempting to utilize a random string (UUID v4) using vue-uuid for existing items and future additions to the list in my to-do list style application. However, I'm uncertain about the correct syntax to use. After installation, I included it ...

Utilize MySQL to populate highcharts with data

Learning the ropes of web programming, I have a personal project to monitor expenses. Simply put, my database stores data on total expenditures for this month and last month. I am able to display it manually (via echo), but I'm struggling to pass the ...

Display a modal before leaving the page?

I need to display a modal message when a user navigates away from the page, triggered by a successful AJAX call. The issue is that if the message loads too quickly, the user may not have enough time to read it before being directed to another page. This is ...

What is the best way to align three images horizontally using bootstrap?

While working on my JavaScript class and creating one-page web apps, I had the idea to create a central hub to store and link them all together. Similar to Android or iOS layouts, I designed a page with icons that serve as links to each app. I managed to ...

Are there any alternative methods to avoid duplication of Navbar link margin classes in Tailwind CSS?

It feels really repetitive to have to add margin classes to each LI manually on a non-dynamically generated menu. It almost seems as messy as using inline style attributes... Is there a more efficient way to handle this? While it may not be a big deal fo ...

Harnessing the power of the bluebird promise library

Within myPeople function, there is a promise function being called as shown below: var myPeople = function(){ var go; return new Promise (function(resolve){ User .getPeople() .then(function(allPeople){ ...

Ways to run evaluations on 'private' functions within an angular service using Karma and Jasmine

In my Angular application, I have a BracketService that consists of various functions for comparing weights and creating brackets based on weight groups. The service includes functions like compareByWeight, filterWeightGroup, and createBracketsByWeightGrou ...

Resize images in PHP and MySQL with precision without distorting the image

I'm looking for a solution to resize images on upload without deforming them. The current code uploads the image and stores it in the database, but I need to add resizing functionality. I'd prefer not to use JavaScript, but if necessary, please i ...