Search code examples
javascriptjqueryjspdatepickerdatatables

input box datepicker not working in all pages of jQuery DataTables


I have jsp page having jQuery DataTables which contain more then 20 pages I'm using textbox in datatable td tags which shows datepicker i.e. check-in /check-out date.

On the 1st page its works perfectly but on the other pages datepicker class is not apply. Here is following code which I used.

HTML code

<table id="tableBookingByBooker">
    <thead class="btn-default">
        <tr>
            <th>checkInDate</th>
            <th>checkInDate</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <input id="checkInDate${data[0]}" />
            </td>
            <td>
                <input id="Text1" />
            </td>
        </tr>
    </tbody>
</table>

JS Code:

$('input[id^=checkInDate]').each(function (index, element) {
    var checkOutDate = (new Date($('#checkOutDate' + $(this).attr('id').substring(11)).val()));
    checkOutDate.setDate(checkOutDate.getDate() - 1);
    $(this).datepicker({
        dateFormat: 'mm/dd/yy',
        maxDate: checkOutDate,
    });
});

$('input[id^=checkOutDate]').each(function (index, element) {
    var checkInDate = (new Date($('#checkInDate' + $(this).attr('id').substring(12)).val()));
    checkInDate.setDate(checkInDate.getDate() + 1);
    $(this).datepicker({
        dateFormat: 'mm/dd/yy',
        minDate: checkInDate,
    });
});

Input box (checkIn/checkout) Datepicker is successfully working in 1st page of datatable but other pages datepicker is not working.

I tried the pagination event and put js code in the function click but it did not work properly


Solution

  • As Ted pointed out, your best bet is to register an on "page change" event. The problem is that a one-time initialization using jquery select won't have an affect on dynamically loaded content.

    There might be other ways, but the one referenced by dataTables looks like this.

    https://datatables.net/reference/event/page

    //Your Check-in UI DatePicker code.
    var checkInInit = function () {}
    //Your Check-out UI DatePicker code.
    var checkOutInit = function () {}
    
    var table = $('#dataTable').DataTable();
    $('#dataTable').on('page.dt', function () {
        checkInInit();
        checkOutInit();
    });