This problem confuses me so much. I want to use JQuery's datepicker in a salesforce page. The code looks like the following.
mytest.html:
<template>
<div data-id="calendar-input">
<input data-id="date-cal" type="text" class="slds-input"></input>
</div>
</template>
mytest.js
import { LightningElement, api, track } from 'lwc';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
import JQuery from '@salesforce/resourceUrl/...';
import JQueryUI from '@salesforce/resourceUrl/...';
export default class MyTest extends LightningElement {
renderedCallback() {
if (!this.scriptLoaded) {
Promise.all([
loadScript(this, JQuery + '/jquery-3.5.1.min.js'),
loadScript(this, JQueryUI + '/jquery-ui-1.12.1/jquery-ui.min.js'),
])
.then(() => {
this.scriptLoaded = true;
})
.catch(error => {
console.log('error load jquery...');
console.log(error);
});
}
jQuery("document").ready(function(){
$(cmp.template.querySelector('[data-id="date-cal"]')).datepicker({
maxDate: ...,
minDate: ...,
defaultDate: ...,
dateFormat: 'dd-mm-yy',
todayHighlight: true,
onSelect: function(dateText, inst) {
console.log('datepicker.onselect');
},
beforeShowDay: function(in_date) {
console.log('datepicker.beforeShowDay');
}
});
})
}
}
The datepicker can show up when clicking the field and beforeShowDay() can be called as well. However, when selecting a date, I got an error "Uncaught Missing instance data for this datepicker" inside JQuery-UI and the page crashed.
However, if I just create an input element dynamically instead of defining it in html. The datepicker works properly. The following codes are my second version:
mytest.html
<template>
<div data-id="calendar-input"></div>
</template>
mytest.js
if (!this.template.querySelector('[data-id="date-cal"]')) {
const div_elm = this.template.querySelector('[data-id="calendar-input"]');
const input_elm = document.createElement('input');
input_elm.id = 'date-cal';
input_elm.setAttribute('data-id','date-cal');
input_elm.className = 'slds-input';
input_elm.type = 'text';
div_elm.appendChild(input_elm);
}
I assume the problem should be salesforce specific but couldn't figure it out. I'm new in salesforce as well as JQuery. Hope someone could give some clue. Thanks.