简体   繁体   中英

jQuery $.change function not working with cloned select

I have a table with a button that adds a row to the bottom by cloning the last row. Each row contains a <select> with a different name (0-9), all <select> objects have the .variable_priority class. When pressing the button, the row gets copied successfully and I manage to change the name correctly (10, 11, 12, etc.), and the row gets the same class since it is a perfect copy.

However, when I execute the following function, I encounter problems with cloned table rows:

$('.variable_priority').change(function() {
    var selections = new Array();
    $(".variable_priority").each(function() {
        selections.push($(this).find('option:selected').val());
    });

    // Iterating on Options of Select
    $('.variable_priority').children('option').each(function() {
        $(this).removeAttr('disabled');

        if($.inArray($(this).val(), selections) !== -1){
            if($(this).val() != 0){
                if($(this).is(':selected')){
                    // nothing
                } else {
                    $(this).attr('disabled', true);
                }
            }
        }
    });
});

The function should run each time I change the selected option of a <select> , though it only runs with the 10 original ones. This function is not executed when I change the option in a cloned row. However, if I change the value in one of the originals, the function runs and it also adds the values from the cloned rows to the selections array.

So for some reason, the code recognizes that the clones have the same class, but it doesn't run when changing their values.

EDIT: short description of the code above; if I change the selected value of a <select> ,the function will add all selected options to an array and disable every selected option in the selects, except in the box where the value itself is selected (if I select '2' in the first box, '2' gets disabled in all other boxes).

Because your select element is dynamic (It is added to the DOM after the initial page load, or to be specific; after the initial event handler attachment) you will need to delegate your change event handler:

$(document).on('change', '.variable_priority', function() {

});

Rather than use document though, you'll want to attach the event handler to the closest static element to .variable_priority .

JSFiddle

I think the code isn't executed on the new clones.

This script is loaded on start. It has to do it over for each new children.. Maybe after adding a new, run this script specific for that new one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM