The nested elements are not triggering the jQuery on click function

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>

Answer №1

The event handler in your code is not targeting the correct elements on the page. By changing it to input, the click event fires, but it returns incorrect IDs. It seems that using $.closest() and $.find() instead of $.parent() resolves the issue.

$("body").on('click', "input", function (event) {
    console.log($(this).closest('div.colors_storage_outer').find('> select').attr('data-id'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>

Answer №2

It has been brought to my attention that there are incorrect selectors.

In addition, I suggest utilizing closest('.colors_storage_outer') with a selector to move up the tree and stop at a specific point. You can also achieve this by using parents('.colors_storage_outer'). Then locate the select element from there.

Consider trying this code:

$("body").on('click', "input.select2-search__field", function (event) {
    console.log($(this).closest('.colors_storage_outer').find('> select').attr('data-id'))
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Achieving a standard POST request with a redirect in ASP.NET MVC using jQuery.Ajax

Currently, I have a JSON object dynamically created on my web page as users add items to it using JavaScript/jQuery. After the user finishes adding items, I aim to send this JSON object via a POST request to a controller action, which will then return a v ...

What is the process for implementing save-exact in bunfig.toml file?

Do bun repositories have a setting similar to .npmrc's save-exact configuration? I attempted to include save-exact = true in bunfig.toml but it did not have any effect. My bun version is 1.0.0. ...

Unable to display shadows in Three.js

I've hit a roadblock with the shadow effect at the moment, despite trying various solutions for hours, it's still not appearing. Can anyone point out what I may have done incorrectly? Below is the code snippet for my current scene: //Setting up ...

Choose dropdown menus that are pre-filled by JSON may require a manual refresh to show the content

Occasionally, I encounter an issue with a JSON file used to populate select boxes, where the items in the drop down fail to display until the page is refreshed. Despite no errors in the console or log, the loading is seamless on most occasions, leaving me ...

Is it possible for the like button to display specific information when clicked?

When working with a looping structure in Ionic and Angular, which includes post content such as text, photos, and videos, I am encountering an issue with selecting specific data when clicking on the like button. How can I ensure that only the data associat ...

Developing an interactive menu for mobile devices utilizing a combination of JSON, HTML, JavaScript, and CSS

Creating a custom dynamic menu for mobile platforms using HTML, JavaScript, and CSS with a JSON object downloaded from the server. Not relying on libraries like jQuery. I've come across advice stating that "document.write" should not be used in event ...

Guide to integrating a Jquery third-party plugin in Angular 7

Recently, I integrated jQuery and a third-party plugin called "stiffChart" into my Angular 7 project. After installing jQuery and the plugin in my project, I declared them in angular.json file as well. However, when trying to call a method from the plugin, ...

Encounter TypeScript error when using getFirebaseAdmin from next-firebase-auth

I am currently utilizing a package called next-firebase-auth. I am encountering an issue when calling getFirebaseAdmin from next-firebase-auth and attempting to use it, specifically when using db as a reference in doc(db). The error message received is: ...

What are the functionalities of display flex and block?

I am having trouble with my CSS setup. I have an outer container that wraps around an inner container, which in turn contains two divs. The inner container has a display property of flex, but for small screen sizes, I want the two divs to stack up and disp ...

Alignment text centrally in a button

I'm currently facing an issue with vertically aligning the text within a button to the center. We are using Bootstrap buttons across different devices and platforms, and everything seems to be working fine except for one specific device where the alig ...

Tips for providing the URL in JSON using Spring MVC

Every time I try to run my code, I encounter an issue where I cannot access the URL specified in the getJSON function. Below is my controller code: @RequestMapping(value = "branch") @Controller public class BranchController { @Autowired(required = true) ...

Is there a way to modify or update the CSS classes and overall styling in .gsp files within the Grails framework?

What is the best way to dynamically update a DOM element's class and styling in response to specific conditions or events occurring in a .gsp file? ...

Sorting arrays with NaN values within objects will not result in a reordering when using the Array

I encountered a situation where I need to reorder items in an array based on the property minLVL of each object within the array. However, I have discovered that this reordering only works if the previous and next items have the required minLVL field. If ...

socket.io and the use of various chat rooms

Is it possible for a client socket in a browser to connect to multiple rooms (3-5) and receive separate messages from each room while using node.js to send messages to all clients in the same room? ...

Reveal the inner workings of functions within the Vuex Plugin

I am currently working on setting up a Vuex plugin where I want to make the undo function accessible for use in my component's click events. // plugin.js const timeTravel = store => { // .. other things function undo () { store.commit(&a ...

Guide on transmitting information from a Kotlin-powered Android app to a React JS application being accessed through a WebView

Imagine you have logged into an Android application using Kotlin and have some data stored. Later, you open a React JS application in a webview. How would you go about transferring the login data from the Android application to the React JS application? ...

Creating metadata for a node/npm module build

Looking for a solution to output JSON with build date and updated minor version number using grunt and requirejs for our application. It seems like this would be a common requirement. Any existing tools that can achieve this? ...

Creating a hierarchical menu structure by splitting strings in an array using an algorithm

I have an array of strings in Javascript that look like this: var array = [{ string: 'path1/path2/path3' }, { string: 'path1/path4/path5' }, { string: 'path1/path2/path6' }, { string: 'path10/path7' }, { s ...

Is there a way to determine the orientation of an image in React-Native, whether it is horizontal or vertical

When working with react-native, I aim to utilize the 'contain' feature for vertical images and the 'stretch' feature for horizontal images. What would be the best way to determine the orientation of an image as either horizontal or vert ...

Is there any other factor aside from the lack of a CSRF token in an AJAX request with Django that could lead to a 403 error?

The primary reason behind the django + ajax 403 error is usually the absence of a csrf token. However, in my scenario, the csrf token is present and a similar ajax function is working fine. I will also provide the backend view function that handles the res ...