Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

95
Visualizações
How to get value of select option inside for loop

I have a select option like this:

<select name="color" id="multipleAttr" class="form-control select-2">
   <option value="blue">
   <option value="red">
</select>

Now in order to return the value of this with jQuery, I did this:

$(".select-2").change(function() {
      var val = $(".select-2").val();
      console.log(val);
});

It works fine and properly shows the value of selected item.

But I wanted to make this more dynamically by using a for loop:

var counters = 2;

for(i=2;i<=counters;i++){
   $(".select-"+i).change(function() {
      var val = $(".select-"+i).val();
      console.log(val);
   });
}

So it should be selecting select-2 class value and returns it as val.

But it prints undefined somehow.

So what's going wrong here? How can I solve this issue?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You should use the event provided to you in the .change method instead of again getting the element from dom in the .change callback.

So your code will be like

var counters = 2;

for(i=2;i<=counters;i++){
   $(".select-"+i).change(function(event) {
      var val = event.target.value;
      console.log(val);
   });
}
about 4 years ago · Juan Pablo Isaza Relatório

0

For that matter, why loop through classnames with numbers? Just set a single class to represent all select elements with the functionality, and then set data-attributes for other info if you need it.

$('.select').change(function() {
  let val = $(this).val();
  let myName = $(this).data('num');
  console.log(`new val is ${val} from ${myName}`);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class='select' data-num='select-1'>
  <option selected></option>
  <option value='33'>33</option>
</select>
<select class='select' data-num='select-2'>
  <option selected></option>
  <option value='55'>55</option>
</select>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda