1

i want to get the data attribute on the second level

$('.filter-select').each(function() {
        console.log($(this).data()) // this gives me all data 
        $(this).on('change', function() {
            console.log($(this).data()) // but here gives me only on that i clicked i want it all
        })

    })
FLASH TUBE
  • 33
  • 4

2 Answers2

1

You can simply:

$('.filter-select').each(function() {
        const allData = $(this).data();
        $(this).on('change', function() {
            // use allData to access all
        })

    })
Luka Cerrutti
  • 667
  • 1
  • 4
  • 9
1

Instead of using each, and then trying to attach event listeners to each .filter-select element use event delegation to attach a listener to a parent element so that it captures the change events from all the .filter-select elements as they "bubble up" the DOM.

$(document).on('change', '.filter-selector', handleChange);

function handleChange() {
  console.log($(this).data());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select data-id="1" class="filter-selector">
  <option selected>Choose (id: 1)</option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>
<select data-id="2" class="filter-selector">
  <option selected>Choose (id: 2)</option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>
Andy
  • 61,948
  • 13
  • 68
  • 95