简体   繁体   中英

datepicker onselect is not working [when datepicker div created dynamically]

I have a datepicker function which seems to be working but its onSelect function is not working i cannot see the alert()

$(function() {
var divContent = '<input type="text" placeholder="Enter date" class="dupInput" id="gl_img_datepicker" readonly=""><button id="gl_img_datepicker_init">Date</button>';


jQuery('body').on('click', '#gl_img_datepicker_init', function(e) {
        jQuery("#gl_img_datepicker").datepicker('show');
 });

//onselect datepicker function 
jQuery('#gl_img_datepicker').datepicker('option', 'onSelect',
   function(dateText, inst) {
     alert('glImgExpiry-->' + dateText);
});
jQuery('body').on('click', '#mybutton', function(e) {
  jQuery("#my_div").append(divContent)
  jQuery("#gl_img_datepicker").datepicker();        
});

});

Check my Fiddle


I have already seen below questions but it did not help.

Datepicker onSelect Not Firing

jquery datepicker onselect not working

Datepicker onSelect not working

jQuery Datepicker onSelect is not working

Thanks

You're trying to assign that event to the field that doesn't exist yet (meaning before the #gl_img_datepicker is being created and inserted into the document). Try it like this (here's the JSFiddle ):

$(function() {
    var divContent = '<input type="text" placeholder="Enter date" class="dupInput" id="gl_img_datepicker" readonly=""><button id="gl_img_datepicker_init">Date</button>';


    jQuery('body').on('click', '#gl_img_datepicker_init', function(e) {
            jQuery("#gl_img_datepicker").datepicker('show');
     });

    jQuery('body').on('click', '#mybutton', function(e) {
        jQuery("#my_div").append(divContent)
        jQuery("#gl_img_datepicker").datepicker();    

        // We have already appended the divContent to the document; we
        // can continue with the actual datepicker event for that field

        //onselect datepicker function 
        jQuery('#gl_img_datepicker').datepicker('option', 'onSelect',
           function(dateText, inst) {
             alert('glImgExpiry-->' + dateText);
        });    
    });

});

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