Ad

Jquery Event Binding Not Working With More Than One Dynamic Object

- 1 answer

On a drop-down menu change of a dynamically added object through AJAX, either add or remove a class. If only 1 object exists the code works, but for some reason more than one will stop it from working.

$('.product_options_container').on('change', '.product_preset_dropdown', function() {
    var conceptName = $(this).closest('.product_option_hidden').children('.product_preset_dropdown').find(":selected").text();
    if(conceptName != 'custom'){
        $(this).closest('.product_option_hidden').children('.product_encapsulation').addClass("hidden");
    }
    else if(conceptName == 'custom'){
        $(this).closest('.product_option_hidden').children('.product_encapsulation').removeClass("hidden");
    }
});

markup

// DIV CONTAINER AJAX IS LOADED TO
<div id="dynamicInputs" class="dynamicInputs"></div>

// AJAX FILE LOADED
<div class='product_option_hidden'>
    <div class="product_preset_inner">
        <div class="product_preset_inner_border">
            <div class="product_preset_dropdown_container">
                <select class="product_preset_dropdown">
                    <option value="custom">custom</option>
                    <option value="preset">preset</option> 
                    <option value="preset2">preset 2</option>
                 </select>
             </div>
         </div>
     </div>
     <div class="product_encapsulation">
         //other content here 
     </div>
 </div>
Ad

Answer

Problem was that

var conceptName = $(this).closest('.product_option_hidden').children('.product_preset_dropdown').find(":selected").text();

was adding an additional custom string output for each additional object added, changed to the below to work

var conceptName = $(this).closest('.product_preset_dropdown').find(":selected").text();
Ad
source: stackoverflow.com
Ad