Change Javascript iterative select background color

Asked

Viewed 80 times

0

Hey, you guys.

I’m having a hard time changing the background color of multiple selects iteratively. I can already change, but I have to manually specify the element index 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>

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 );
    })
})
  • Thank you very much! I didn’t know the 'for of'. I was using the for and it wasn’t working.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.