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 = "";
}
}
}
}
}
}
}