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

125
Visualizações
Javascript syntax to add a loop variable inside another variable

I am looking to incorporate the following id variables: e1, e2, etc. into a loop.

What is the right syntax to handle the '#e'+i and '#e'+i elements, to avoid writing multiple functions eg. : $(document).on('change', '#e1', function() { and var exp = 'e1';

PS: Currently, the below on change function is not triggered.

for (var i = 0; i < 10; i++) {      
        
$(document).ready(function() {          
              $(document).on('change', '#e'+i, function() {
                if ($("#e"+i).is(":checked")) {     var chk = $('#e'+i).val(); var exp = 'e'+i; }
                else {  chk = 0 ;   var exp = 'e'+i;    }
                $.ajax({
                        url: "modify.php",
                        method: "POST",
                        data: {check: chk, experience: exp },
                  });
              });       
            })
            ;
        }       
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You're making your life more difficult and your code too complicated. Consider this approach, which uses a class name rather than dynamic id's.

$(document).ready(function() {
  $('body').on('change', '.changeable', function() {
    let data = {
      check: $(this).is(":checked") ? $(this).val() : 0,
      experience: $(this).data('ref')
    }
    return console.log(data);
    $.ajax({
      url: "modify.php",
      method: "POST",
      data: data,
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='checkbox' data-ref="e1" class="changeable" value='val1' />
<input type='checkbox' data-ref="e2" class="changeable" value='val2' />
<input type='checkbox' data-ref="e3" class="changeable" value='val3' />

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