I use AMsul Pickadate and try to add a custom header by using jquery .prepend
It works fine, but when I use 2 datapickers on one page, to the first one my custom header is added twice, what make it looks ridiculous.
This is my js code:
$.extend($.fn.pickadate.defaults, {
selectMonths: true, // Creates a dropdown to control month
selectYears: 15, // Creates a dropdown of 15 years to control year,
onRender: function () {
var year = $('.datepicker').pickadate('picker').get('highlight', 'yyyy');
var day = $('.datepicker').pickadate('picker').get('highlight', 'dd');
var month = $('.datepicker').pickadate('picker').get('highlight', 'mmm');
var labelday = $('.datepicker').pickadate('picker').get('highlight', 'dddd');
console.log(year, day, month, labelday);
$('.picker__header').prepend('<div class="picker__date-display"><div class="picker__weekday-display">' + labelday + '</div><div class="picker__month-display"><div>' + month + '</div></div><div class="picker__day-display"><div>' + day + '</div></div><div class="picker__year-display"><div>' + year + '</div></div></div>');
}
});
And this is the result when I use 2 datapickers on one page:
My html markup looks like that:
<!-- First datapicker-->
<input placeholder="Selected date" type="text" id="input_from" class="form-control datepicker">
<!--Second datapicker -->
<input placeholder="Selected date" type="text" id="input_to" class="form-control datepicker">
And I initialize the picker via js:
// Datapicker initialization
$('.datepicker').pickadate();
How can I make it to always add only one custom header to each datapicker, even if there is more then one?
The jQuery prepend method will prepend what you give it to all elements matching the selector:
$('.picker__header')
This will prepend to both .picker__header
s it can find every time it is fired. By putting it in the render callback, it is being called for every time a datepicker is rendered. Twice, therefore, because you have 2 datepickers.
The best thing would be to prepend in a callback that is only called once, or to increment a counter on the render callback. Something like:
var dateCounter = 0;
...
onRender: function () {
dateCounter++;
if (dateCounter === 2) {
$('.picker__header').prepend(...
}
}
But there are lots of ways to do this. Maybe there's something in the pickadate.js API that might be more elegant?