Search code examples
jqueryjquery-uijquery-templates

Jquery Template textbox not showing datepicker


I am using Datepicker on one of the the textbox in Jquery template but its not popping up. Outside of the template working fine. Below is what I want to do.

jQuery().ready(function () {

  //$("#HireDate").datepicker();
  $("#HireDate").datepicker({dateFormat:'dd-mm-yy', showAnim:'fadeIn'})


});

<script id="UserDetailTemplate" type="text/x-jquery-tmpl">

<table style="width:100%;">
        <tbody>             

                        <tr>
                            <td style="width:25%;font-weight:bold;">HireDate:</td>
                            <td><input type="text" id="HireDate" value="${ HireDate }" /></td>
                        </tr>  

                    </table>                         
                    </td>
            </tr>
        </tbody>
</table> 
 </script> 

Solution

  • The #HireDate element doesn't exist until you use the template to insert some content into the page. So, when you try to bind the datepicker when the DOM is ready, $('#HireDate') returns an empty list (i.e. $('#HireDate').length == 0) and nothing useful happens.

    The solution is to bind the datepicker after the template is filled in and inserted into the page. Something like this:

    $('#UserDetailTemplate').tmpl(data).appendTo('#something');
    $('#HireDate').datepicker({ dateFormat: 'dd-mm-yy', showAnim: 'fadeIn' });