When I attempt to retrieve the attributes of the parent element from a clicked element, I run into issues with dynamically added elements via jQuery. Below is the code snippet for the click event that is not functioning as expected:
$("body").on('click', ".colors_storage input", function (event) {
console.log($(event.target).parents().find('div.colors_storage_outer > select').attr('data-id'))
/*console.log(parent.attr('data-id'))
console.log(parent.attr('name'))*/
})
Although this code technically works, it only returns the id 855 regardless of which input element is clicked.
$("body").on('click', $(".colors_storage input"), function (event) {
console.log($(event.target).parents().find('div.colors_storage_outer > select').attr('data-id'))
/*console.log(parent.attr('data-id'))
console.log(parent.attr('name'))*/
})
This is the HTML structure in question:
<div class="colors_storage_outer">
<select data-id="855" name="colors[]" multiple="" class="form-control colors_storage bulk-colors select2-hidden-accessible" data-placeholder="Colors" tabindex="-1" aria-hidden="true"></select>
<span class="select2 select2-container select2-container--default select2-container--above select2-container--focus" dir="ltr" style="width: 121.25px;">
<span class="selection">
<span class="select2-selection select2-selection--multiple" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="-1">
<ul class="select2-selection__rendered">
<li class="select2-search select2-search--inline">
<input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox" aria-autocomplete="list" placeholder="Colors" style="width: 119.917px;">
</li>
</ul>
</span>
</span>
<span class="dropdown-wrapper" aria-hidden="true"></span>
</span>
</div>
<div class="colors_storage_outer">
<select data-id="853" name="colors[]" multiple="" class="form-control colors_storage bulk-colors select2-hidden-accessible" data-placeholder="Colors" tabindex="-1" aria-hidden="true"></select>
<span class="select2 select2-container select2-container--default select2-container--above select2-container--focus" dir="ltr" style="width: 121.25px;">
<span class="selection">
<span class="select2-selection select2-selection--multiple" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="-1">
<ul class="select2-selection__rendered">
<li class="select2-search select2-search--inline">
<input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox" aria-autocomplete="list" placeholder="Colors" style="width: 119.917px;">
</li>
</ul>
</span>
</span>
<span class="dropdown-wrapper" aria-hidden="true"></span>
</span>
</div>