简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM