1252748
1252748

Reputation: 15362

jquery on does not react to element added by clone()

I was under the impression that jquery's on() reacted to events attached elements dynamically added to the dom (via ajax or cloning, etc). However, the following is only working for the element attached to the dom at page load. The other copy I make of it using clone() is not being, well, 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');
        }
    });
});

Code for cloning:

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

HTML for dropdown (contents added by jquery db query on document ready)

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

Thank you for any insight!

Upvotes: 0

Views: 381

Answers (4)

Adriano Carneiro
Adriano Carneiro

Reputation: 58595

Change this line:

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

to this:

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

Upvotes: 1

Blazemonger
Blazemonger

Reputation: 92893

Either delegate the event instead:

$(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');
    }
});

Or better yet, use .clone(true) to clone with events. (Note: this will only work if you're cloning AFTER the event handler is attached.)

Upvotes: 6

James Montagne
James Montagne

Reputation: 78630

It does, but not in the way that you think. When used as you have used it:

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

It is really not different than using .change(). What you are looking for is event delegation. This takes the following form:

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

Where <selector to static ancestor> is a selector to a static ancestor of the dynamically added elements. (one that is not dynamically created) As a last resort document can be used here. However for performance, this should be the closest static ancestor element.

Upvotes: 3

Bergi
Bergi

Reputation: 664217

jquery's on() reacted to events attached elements dynamically added

No - or at least, only if you use it with delegated events. The live method did always delegate events to the document.

Upvotes: 2

Related Questions