janhartmann
janhartmann

Reputation: 15003

Change event not firing

I have cloned a table (with selects) to copy to somewhere else. This works great and I manage to change the ID's with no worries. The problem is that if I try to bind a change event to each of them, will it never fire? Is there a obvious mistake here? Thank you.

<script type="text/javascript">
            $(document).ready(function () {
                var variants = $("table.variantselection").clone(false);

                variants.find("select").each(function (i, o) {
                    $(this).attr("id", $(this).attr("id") + "_popup");
                });

                variants.find("select").change(function () {
                    alert($(this).val()); // never reaches this alert
                });

                variants.appendTo("#popup_variants");               
            });
        </script>

Upvotes: 0

Views: 1279

Answers (3)

Mark Coleman
Mark Coleman

Reputation: 40863

Since it appears that #popup_variants is the parent element on your table, you might be better off to use .delegate()

$(document).ready(function() {

$("#popup_variants").delegate("select", "change", function(){
  alert($(this).val());
});

var variants = $("table.variantselection").clone(false);

variants.find("select").each(function(i, o) {
    $(this).attr("id", $(this).attr("id") + "_popup");
});

variants.appendTo("#popup_variants");

});

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

Change false to true to copy the event handlers with the DOM element

var variants = $("table.variantselection").clone(true);

Failing that, use the live() event to bind:

variants.find("select").live("change", function () {
    alert($(this).val());
});

Upvotes: 1

Alnitak
Alnitak

Reputation: 339786

Try binding the .change() function after you've reattached the clone to the DOM.

Upvotes: 0

Related Questions