0

Olá, galera.

Estou com uma dificuldade de mudar a cor de fundo de vários selects de modo iterativo. Já consigo mudar, mas tenho que especificar o índice manualmente do elemento para isso acontecer. Aqui está um exemplo do que estou fazendo:

 <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 Resposta 1

0

Basta utilizar um laço de repetição, por exemplo: for, forEach, while etc.

Exemplo com for..of:

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

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

Exemplo com for..in:

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

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

Exemplo com forEach:

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

selects.forEach( select => {
    select.addEventListner("change", _ => {
        select.classList.add( this.options[this.selectedIndex].className );
    })
})
1
  • Muito obrigado! Não conhecia o 'for of'. Estava usando o for e não tava dando certo. 24/08/2018 às 21:15

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .