简体   繁体   中英

jQuery - dynamically created select boxes not triggering function when value is selected

I have some code that dynamically creates a select drop down menu. I would like each select drop down menu to have an "onchange" ability to call a different function once selected... so far I am having trouble doing this... help is appreciated.. thanks!

function createSections(num) {
        var value = num.value;
        alert(value);
    }

    jQuery('#number-of-units').change(function() {

         var num = parseInt(jQuery(this).val());
         var container = jQuery('<div />');
         var i = 1;

         for(i; i <= num; i++) {

             container.append('<select onchange="createSections(this)" class="create-course-select-element"><option disabled selected value="none">--</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option></select>');

         }

         jQuery('#display-unit').html(container).hide();
         jQuery('#display-unit').fadeIn(1500);

    });

You can use the jQuery function "on".

This will fire the event for all <select> into your <body>

jQuery('body').on('change', 'select', function() { alert('fire the event!'); });

https://api.jquery.com/on/

My 2 cents before this is closed:

You can also call the change() function after you append the select element to the document.

MapSelects()  //called AFTER adding the select to the document
function MapSelects(){
    $('select.create-course-select-element').off();
    $('select.create-course-select-element').change(function(){
        createSections($(this).val());
    });
}

http://jsfiddle.net/Z5vLq/

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