PhantomM
PhantomM

Reputation: 845

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

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/

Upvotes: 1

Views: 1650

Answers (1)

Meligy
Meligy

Reputation: 36594

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();
}

Upvotes: 1

Related Questions