Change background color of the iterative JavaScript select

0

Hello, guys.

I'm having a hard time changing the background color of multiple selects in iteratively. I can already change, but I have to manually specify the index of the element for this to happen. Here's an example of what I'm doing:

 <select class="selectpicker bg-success">
            <option class="bg-success" value="caixa">Em caixa</option>
            <option class="bg-warning" value="depositado">Depositado</option>
            <option class="bg-info" value="pago">Pago</option>
            <option class="bg-danger" value="devolvido">Devolvido</option>
 </select>

 <select class="selectpicker bg-success">
            <option class="bg-success" value="caixa">Em caixa</option>
            <option class="bg-warning" value="depositado">Depositado</option>
            <option class="bg-info" value="pago">Pago</option>
            <option class="bg-danger" value="devolvido">Devolvido</option>
 </select>


<script>
    var select = document.querySelectorAll('select');
    // console.log(select[1]);

    var allselect = []
    for (i = 0; i < select.length; i++) {

        allselect.push(select[i]);

    }

    allselect[0].onchange = function () {

        allselect[0].className = this.options[this.selectedIndex].className;

    }

    allselect[1].onchange = function () {

        allselect[1].className = this.options[this.selectedIndex].className;

    }

</script>
    
asked by anonymous 24.08.2018 / 21:06

1 answer

0

Just use a repeat loop, for example: for , forEach , while etc.

Example with for..of :

const selects = document.querySelectorAll('select');

for (let select of selects) {
    select.addEventListner("change", _ => {
        select.classList.add( this.options[this.selectedIndex].className );
    })
}

Example with for..in :

const selects = document.querySelectorAll('select');

for (let key in selects) {
    select.addEventListner("change", _ => {
        selects[key].classList.add( this.options[this.selectedIndex].className );
    })
}

Example with forEach :

const selects = document.querySelectorAll('select');

selects.forEach( select => {
    select.addEventListner("change", _ => {
        select.classList.add( this.options[this.selectedIndex].className );
    })
})
    
24.08.2018 / 21:26