简体   繁体   中英

jQuery: Running multiple datepicker's on dynamically created inputs

I am trying and failing to add datepicker to inputs that are created dynamically.

They have different id's and I am specifically targeting the new input and calling datepicker.

In the jsFiddle example below it only works for the 2nd input (first one datepicker is called on) and does not work for any others after that.

Here is the jsFiddle: http://jsfiddle.net/TJfbc/1/ Press the plus sign to add more.

Note: I am aware the first element will not have the datepicker.

Here's a cleaner alternative

$(function() {
    //append one handler to the parent to detect append actions
    $('.action_items').on('click', '.expand', function() {
        var $el = $(this);
        $el.parent()
            .clone()
            .appendTo($el.closest('.action_items'))
            .find('input')
            .removeClass('hasDatepicker')
            .each(function () {
                newName = this.name.slice(0,6) + (parseInt(this.name.slice(6)) + 1);
                this.name = newName;
                this.id = newName;
             })
            .datepicker();

        //change text, remove original handler, add the remove handler
        $el.text('-').off('click').on('click',function(){
            $(this).parent().remove();
        });
    })
});​

http://jsfiddle.net/TJfbc/27/

You need to "refresh" the previous textfield that has already class of 'hasDatepicker' before you can initialize a new one

new_action_item.find('.dpDate').removeClass('hasDatepicker').datepicker()

An improvement on readability:

  • No need to repeatedly call $() on new_action_item since clone() returns an already jQuery object

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