jquerycordovajquery-mobiledatepickerdatebox

Jquery Mobile DateBox is not showing time picker if created dynamically


I am using Jquery Mobile DateBox plugin for date/time picker in my cordova Application. It works fine if written as it is HTML file. The problem comes if I clone a div which has DateBox input and append it to another div. Time picker is not poping up on tap of timer icon.

The div which I am cloning is,

<div class="time-picker-template">

    <input class="time-input day-time-picker" type="text" data-role="datebox" data-options='{"mode":"timebox", "useNewStyle":true}' />

</div>

The way I clone is ,

var dayTimePicker = $("#page-add-reminder .time-picker-template").clone();

$("#page-add-reminder #time-picker-block").append(dayTimePicker);

It renders the DateBox input field but it is disabled. When I inspect the element, It shows,

<input class="time-input day-time-picker" type="text" data-role="datebox" data-options="{"mode":"timebox", "useNewStyle":true}" readonly="readonly">

I suspect the readonly property initially but the input field will be readonly only. On tap of time icon which resides next to input field filled the time in other case.

I compared the DOM element of both cloned element and general TimeBox element. Both looks same. The first didn't work but the later works. Where am I missing ? Can any suggest me how to make this work ?


Solution

  • When cloning the datebox, you should put your templates outside the page so that jQM does not enhance then before you clone and add them to the page. Here is a working demo:

    <div id="templates">
        <div class="time-picker-template">
            <input class="time-input day-time-picker" type="text" data-role="datebox" data-options='{"mode":"timebox", "useNewStyle":true}' />
        </div>
    </div>
    
    <div data-role="page" id="page1">
        <div role="main" class="ui-content">
            <button id="btnAdd">Add timepicker from template</button>
            <div id="time-picker-block"></div>
        </div> 
    </div>  
    
    $(document).on("pagecreate","#page1", function(){     
        $("#btnAdd").on("click", function(){
            var dayTimePicker = $("#templates .time-picker-template").clone();
            $("#time-picker-block").append(dayTimePicker).enhanceWithin();        
        });
    });
    

    When you click the button, the un-enhanced template is cloned and added to the page, then we call enhanceWithin() to tell jQM to ehance the controls within the block.

    FIDDLE

    You could also have your template as a string in the script.