jQuerry's on method fails to respond to newly added elements through the clone() function

I always thought that jquery's on() function would handle events for dynamically added elements in the DOM, such as those added via ajax or cloning. However, I'm finding that it only works for elements already attached to the dom at page load. Cloned copies of these elements using clone() are not being handled.

$(document).ready(function () {
    $('.ship_via_dropdown').on('change', function () {
        console.log($(this));
        if ($(this).hasClass('prev_change')) {
            console.log('has');
        } else {
            $(this).addClass('prev_change');
            console.log('hasn\'t');
        }
    });
});

Here is the code used for cloning:

$(document).ready(function(){
    var form1 = $('.line_item_wrapper').children().clone(); 
    $('#new_line_content_1').html(form1);
});

This is the HTML structure for the dropdown (contents added dynamically by a jquery db query on document ready):

<span class="select ship_via_select_container">
    <select class="ship_via_dropdown ship_via_dropdown_1">
    </select>
</span>

Any tips or insight on this issue would be greatly appreciated!

Answer №1

You have two options to handle the event:

$(document).on('change', '.ship_via_dropdown', function () {
    console.log($(this));
    if ($(this).hasClass('prev_change')) {
        console.log('has');
    } else {
        $(this).addClass('prev_change');
        console.log('hasn\'t');
    }
});

Alternatively, you can utilize .clone(true) for cloning along with events. (Keep in mind: this method only works if you're cloning AFTER the event handler is attached.)

Answer №2

Yes, it does work but not as you might expect. When utilizing it in the following manner:

$('.ship_via_dropdown').on('change',

Essentially, this is no different than simply using .change(). What you actually need to implement is event delegation, which looks like this:

$("<selector to static ancestor>").on('change', '.ship_via_dropdown', function () {

Here,

<selector to static ancestor>
should point to a static ancestor of the dynamically inserted elements (i.e., one that is not created dynamically). As a final option, you can use document here but for better performance, choose the closest static ancestor element.

Answer №3

When using jquery's on(), it will respond to events even on elements that are dynamically added.

However, this is only true if you use delegated events. The old live method always delegated events to the document.

Answer №4

Modify the following line:

$('select.ship_via_dropdown').on('change', function () {

to read like this:

$(document).on('change',"select.ship_via_dropdown", function () { 

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

What could be the reason for my post jQuery Ajax request sending JSON data?

After downloading some code, I came across the following fragment: function FetchCommentsBySessionIDWCF_JSON() { varType = "POST"; varUrl = "service/CommentSessionIDWCFService.svc/FetchCommentsByPost"; varData = ' ...

Using Swagger with Next.js

Is it possible to generate Swagger documentation for API routes in NEXT.js? I am working with Next.js for both front-end and back-end tasks, and I am interested in creating a Swagger documentation for the APIs implemented in Next.js. ...

Node js server for world's warm greetings

I have been attempting to utilize Node.js for hosting a web server on a dedicated PC, but unfortunately I am unable to access it from anywhere outside of my local network. After researching online, the general consensus is that all I need to do is enter t ...

The spinning loading wheel on Firefox persists even after submitting the iFrame

I have encountered a strange issue with Firefox that I can't seem to figure out. In my system, AJAX is used to send data to a PHP API. However, when file uploads are involved, Firefox does not use XMLHttpRequest() and instead reverts to submitting the ...

Turn off the chrome react DevTools when deploying to production to ensure the

I have successfully browserified my react app for production using gulp and envify to set up NODE_ENV. This has allowed me to remove react warnings, error reporting in the console, and even disable some features like the require of react-addons-perf. Afte ...

Issues with retrieving data from Firestore and storing it into an array in a React

Struggling to fetch data from my firestore and display it on the webpage. Despite trying all possible solutions and searching extensively, I am unable to get it working. When using the code below, nothing appears on the website. However, if I switch to th ...

The subsequent middleware in express next() is failing to trigger the next middleware within the .catch() block

I'm facing a puzzling issue with my POST route. It's responsible for creating transactions through Stripe using the Node package provided by Stripe. Everything works smoothly until an error occurs, such as when a card has insufficient funds. Whe ...

Changing the .load function based on user input

Can I replace a .load text with one that can be updated by a user using form input or similar method? My goal is to create a code that retrieves data using unique div IDs (specific to each employee) containing information within tables across various HTML ...

create a JavaScript array variable for posting items

My goal is to use this javascript to make four posts for the 'var msg' array. However, it currently posts 'encodeURIComponent(msg[i])' four times instead. How can I resolve this issue? var msg = ['one', 'two& ...

Waveform rendering in HTML5 using wavesurfer.js struggles to handle large mp3 files

Recently, I was considering incorporating wavesurfer.js into one of my projects so I decided to explore the demo on To test it out, I uploaded a large mp3 file (approximately 2 hours long) onto the designated area in the middle of the page. It appeared to ...

Is there a way to automatically close one menu when another is opened by clicking?

When all other search results have failed to solve my issue, I resort to posting my own question. My problem involves opening hidden submenus in a website's main menu. However, when I open multiple submenus, they just stack above each other. Ideally, ...

Difficulty comprehending the response from an AJAX post is being experienced

I'm currently working on a website and facing an issue connecting JavaScript with PHP using AJAX. Specifically, I'm struggling with reading the AJAX response. My PHP script contains the following code: <?php echo "1"; In addition, I have a ...

The method provided by the FullScreen API is not effective in cancelling the fullscreen mode

After testing my code in Google Chrome, I encountered the following error message: Uncaught TypeError: Object #<HTMLDivElement> has no method 'webkitCancelFullScreen' Interestingly, I also received a similar error while running the code i ...

I am wondering if it is feasible for a POST route to invoke another POST route and retrieve the response ('res') from the second POST in Express using Node.js

Currently, I have a POST route that triggers a function: router.route('/generateSeed').post(function(req,res){ generate_seed(res) }); UPDATE: Here is the genrate_seed() function function generate_seed(res) { var new_seed = lightwallet. ...

Dynamically adjust the gage value

Currently, I am working on a fitness application that involves showcasing BMI data using a gauge. However, I am struggling to figure out how to dynamically change the value of the gauge. In addition, when trying to implement the gauge script on button cl ...

The Xero Node OAuth Authorize Callback URL is malfunctioning after granting access

When utilizing the xero-node library to produce a Request Token using the getRequestToken function, the URL provided does not automatically redirect the user to the designated callback address specified in the configuration. Instead, a screen displaying a ...

Learn how to make a mesh in Three Js React refract its environment while keeping the background hidden from the camera

I've been grappling with this challenge for quite some time now, so any assistance would be highly valued! My aim is to create the illusion of an image being confined within a mesh structure. My initial idea was to utilize a mesh with defined thickne ...

Retrieve the data stored in an array of objects

code props.thumbnails.forEach(value=>{ console.log(value.photo.thumbnail_url); }) error TypeError: Cannot read property 'thumbnail_url' of undefined Trying to loop through props.thumbnails array and access the thumbnail_url pro ...

Attaching a click event to a nested element within an AngularJS directive

I am currently working with the following directive. (function () { 'use strict'; angular.module('ap.App') .directive('clearCancelFinishButtonsHtml', function () { return { scope: { ...

Broadening the capabilities of jQuery through a versatile function

Currently, I am in the process of developing a generic function for my website using jQuery that will be utilized across the entire site to display success or error messages. After careful consideration, I have decided to transform this function into a plu ...