Ad

How To Toggle Selected True Or False Onchange Of Select Tag?

- 1 answer

I have a select tag with n-number of options. I need to set the selected option to true and set others to false. The true should toggle when the onchange function triggers.

My code is below:

let techDropClone = document.getElementsByTagName("select")[0];
let opt = techDropClone.options;
opt[techDropClone.selectedIndex].setAttribute("selected",true);

I know that the above code will not toggle the true but I don't know how to achieve this.

Ad

Answer

a vanilla js solution could be:

let techDropClone = document.getElementsByTagName("select")[0];
let opt = techDropClone.options;

for(var i=0; i<opt.length; i++){
    if(i == techDropClone.selectedIndex){
        opt[i].setAttribute("selected",true);
    }else{
        opt[i].setAttribute("selected",false);
    }
}

Optimizations are possible, but i don't know well enough your data structure

Ad
source: stackoverflow.com
Ad