Search code examples
javascriptjquerydatetimepickereventhandler

Jquery functions not working on dynamically loaded contents(not binding function)


I have a question in javascript, that I have a form which has add and delete button, on clicking them, some of the form fields gets repeated and deleted as per button click, In those fields I have also datetimepicker, and I want that it should work in generated fields also, but its not working, although I have used class instead of Id for giving them functions like

    $(function () {
    var now = new Date();
    $('.time_in').datetimepicker({
        defaultDate: now,
        format: 'HH:mm'
    });
});

But it is working only in the first field instead of all the fields, I have also attached some event handlers after changing the values of datetimepicker, but I don't have issues with them, I know that how to do it.

I just wanted to ask that how to give function or initialize fields with datetimepicker..

Below is the Screenshot

Scenario


Solution

  • Hi since you are creating textboxes dynamically you should use event delegation, use jQuery's on() method (requires jQuery version 1.7x+).

    Add

     $('body').on('focus',".time_in'", function(){
            $(this).datepicker();
        });
    

    here is a small demo http://jsfiddle.net/SJ7bJ/1013/