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

112
Visualizações
Get next html element custom attribute with jquery

I have html:

<div>
   <label>Select1</label>
   <select class="selectme" data-field-name="select1">
     <option selected>Select Me</option>
   </select>
</div>
<div>
   <label>Select2</label>
   <select class="selectme" data-field-name="select2">
     <option selected>Select Me</option>
   </select>
</div>

and i want to get custom attribute (data-field-name) of this and next select on every change event. I can get this select attr, but i can't get next select attr, i tryed to do, like this but it not works. I use jquery:

$('.selectme').on('change', function () {
    var selectOneName = $(this).attr("data-field-name");
    var selectTwoName = $(this).next('select').attr("data-field-name");
});

How i can do that? Thanks!

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

0

The issue is because next() is used to retrieve sibling elements, and the select are not siblings.

To do what you require you need to traverse the DOM to find the content you want to retrieve. One way to do this would be to use closest() to get the parent div, then next() and find(), something like this:

$('.selectme').on('change', e => {
  let $select = $(e.target);
  var fieldName = $select.data('field-name');
  console.log(fieldName);

  var $nextSelect = $select.closest('div').next().find('select');
  let nextFieldName = $nextSelect.data('field-name');
  console.log(nextFieldName);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div>
  <label>Select1</label>
  <select class="selectme" data-field-name="select1">
    <option selected>Foo</option>
    <option>Bar</option>
  </select>
</div>
<div>
  <label>Select2</label>
  <select class="selectme" data-field-name="select2">
    <option selected>Foo</option>
    <option>Bar</option>
  </select>
</div>

Note that I corrected the issues in your HTML as part of the above example. I assumed they were just errors caused by transposing the code in to your question.

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