Adding new row, binding of datepicker to cloumn works in weird manner

天涯浪子 提交于 2019-12-11 04:42:15

问题


I am trying to add a new row on button click. In my new row there is one Textbox with which I want to bind datepicker but not able to. Please help me to resolve this issue.

<table>
     <tr>
     <td><button type="button" onClick ="addRow(this)">Add</button></td>
     </tr>
     <tr>
     <td><input type="text" name="installDate" value="" class ="date"/> </td>        
     </tr>
</table>

JavaScript

$(document).on('click', function() {
$('.date').each(function() {
        $(this).datepicker();
});
});

function addRow(btn) {         
    var parentRow = btn.parentNode.parentNode;
    var table = parentRow.parentNode;
    var rowCount = table.rows.length;
    var lastRow = table.rows[rowCount - 1];
    var rowClone = lastRow.cloneNode(true);
    table.appendChild(rowClone);
    $('.date', rowClone).datepicker(); // Code to fix the problem
}

Seq1: Add Row => Click on textbox of newRow, calender pops up and everything works fine.

Seq2: 1. Click on document and then try on textbox of original row, then calender pops up. 2. Add new row. 3. now click on textbox of new row, calender never pops up to select the date.

Attaching JSFiddle for reference http://jsfiddle.net/wAyhm/9/


回答1:


This is what you are looking for:

How to clone elements that have been bound by a jQuery UI Widget?

Working fiddle:

http://jsfiddle.net/Meligy/DKtA6/6/

window. addRow = function addRow(btn) {         
    var parentRow = btn.parentNode.parentNode;
    var table = parentRow.parentNode;
    var rowCount = table.rows.length;
    var lastRow = table.rows[rowCount - 1];
    var lastDatePicker = $('.date', lastRow);
    var rowClone = $(lastRow).clone(true);
    var datePickerClone = $('.date', rowClone);
    var datePickerCloneId = 'test-id' + rowCount;
    datePickerClone.data( "datepicker", 
        $.extend( true, {}, lastDatePicker.data("datepicker") ) 
    ).attr('id', datePickerCloneId);
    datePickerClone.data('datepicker').input = datePickerClone;
    datePickerClone.data('datepicker').id = datePickerCloneId;
    $(table).append(rowClone);
    datePickerClone.datepicker();
}


来源:https://stackoverflow.com/questions/17286100/adding-new-row-binding-of-datepicker-to-cloumn-works-in-weird-manner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!