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
})
})
CodePudding user response:
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" >
<option selected>Choose (id: 1)</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select data-id="2" >
<option selected>Choose (id: 2)</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
CodePudding user response:
You can simply:
$('.filter-select').each(function() {
const allData = $(this).data();
$(this).on('change', function() {
// use allData to access all
})
})