Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!