[SalesForce] Custom Date picker in Lightning component

I'm trying to use Jquery Date Picker "https://jqueryui.com/datepicker/" in Salesforce Lightning Component.
I've included required library files.
It is working in Visualforce Page. But the same is not working in Lightning Component see below error image.

Can anyone please advice me on this?

Lightning Component and Controller

<aura:component >
<ltng:require scripts=" /resource/jqueryDatePicker1/jqueryDatePicker1/jquery-1.12.4.js,
                       /resource/jqueryDatePicker1/jqueryDatePicker1/jquery-ui.js"
              />
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<p>Date: <input type="text" id="datepicker"/></p> 

({

  doInit : function(component, event,helper) {
    console.log('doneRendering');
    console.log(jQuery);
    var j$ = jQuery.noConflict();
    j$( "#datepicker" ).datepicker({
        changeMonth: true,
        changeYear: true
    });

}

})
enter image description here

VF Page

 <p>Date: <input type="text" id="datepicker"/></p>

<script>
var j$ = jQuery.noConflict();
j$( function() {
    j$( "#datepicker" ).datepicker({
        changeMonth: true,
        changeYear: true
    });
} );

enter image description here

Best Answer

Component's init handler is called long before scripts are loaded. So, You need to add afterScriptsLoaded={!c.methodName} to the <ltng:require /> tag, which inturn invokes the controller method where you can access the jQuery.

Here's an example:

component:

    <aura:component>
        <ltng:require scripts="/resource/jqueryDatePicker1/jqueryDatePicker1/jquery-1.12.4.js,/resource/jqueryDatePicker1/jqueryDatePicker1/jquery-ui.js"
                      afterScriptsLoaded="{!c.setScriptLoaded}"/>

    </aura:component>

controller:

({
    "setScriptLoaded" : function(cmp){
        console.log(jQuery);
    }
})

Right place to do DOM Manipulation is in the Renderer. You can use the afterRender to access the DOM.

Renderer:

afterRender: function(component, helper) {
    this.superAfterRender();
    console.debug('afterRender $: ',jQuery);
}

If using afterRender doesn't work, look at this answer this might help.

Related Topic