Add custom classname to jquery calendar cell - javascript

I am using Jquery calendar. I am trying to insert a new class name to each cell of calendar. It gets added but it is getting removed as and when the calendar is clicked.
Basically it refreshes the calendar on every click so newly added class is getting removed on refresh.
How do I retain the class name?
here is my code
$(function() {
$('#custom-date-format').multiDatesPicker({
dateFormat: "y-m-d"
});
$('.ui-state-default').addClass("calendar_bg");
});
Demo

Use callback functions of Datepicker Widget
$('#DatePicker').datepicker({
//The calendar is recreated OnSelect for inline calendar
onSelect: function (date, dp) {
updateDatePickerCells();
},
onChangeMonthYear: function(month, year, dp) {
updateDatePickerCells();
},
beforeShow: function(elem, dp) { //This is for non-inline datepicker
updateDatePickerCells();
}
});
updateDatePickerCells();
function updateDatePickerCells(dp) {
/* Wait until current callstack is finished so the datepicker
is fully rendered before attempting to modify contents */
setTimeout(function () {
$('.ui-datepicker td > *').each(function (idx, elem) {
$(this).addClass("calendar_bg");
});
}, 0);
}
See Demo
For multiDatesPicker()
$(function() {
$('#from-input').multiDatesPicker({
beforeShow: function(elem, dp) {
updateDatePickerCells();
}
});
});

Why don't you suppose to override the existing .ut-state-default background-color instead of going for adding new one?
.ui-state-default{background: #ffeb3b !important}

It's a known tricky jQuery UI calendar issue, see this question jQuery ui - datepicker prevent refresh onSelect
Anyway, the fix is to add inst.inline = false; on select, like this
$('#custom-date-format').multiDatesPicker({
dateFormat: "y-m-d",
onSelect: function(date, inst){
inst.inline = false;
$('.ui-state-default').addClass("calendar_bg");
}
});
See a demo, note however, that it throws an error in multidatespicker.js. There seems to be an issue with this plugin.

It would be better to use the existing class name and override its default styling.
Add this style .ui-widget-content a.ui-state-default { background: #ffeb3b }
Here is the same demo

Related

jQuery's datepicker not showing up after validation error [duplicate]

I have dynamically created textboxes, and I want each of them to be able to display a calendar on click. The code I am using is:
$(".datepicker_recurring_start" ).datepicker();
Which will only work on the first textbox, even though all my textboxes have a class called datepicker_recurring_start.
Your help is much appreciated!
here is the trick:
$('body').on('focus',".datepicker_recurring_start", function(){
$(this).datepicker();
});​
DEMO
The $('...selector..').on('..event..', '...another-selector...', ...callback...); syntax means:
Add a listener to ...selector.. (the body in our example) for the event ..event.. ('focus' in our example). For all the descendants of the matching nodes that matches the selector ...another-selector... (.datepicker_recurring_start in our example) , apply the event handler ...callback... (the inline function in our example)
See http://api.jquery.com/on/ and especially the section about "delegated events"
For me below jquery worked:
changing "body" to document
$(document).on('focus',".datepicker_recurring_start", function(){
$(this).datepicker();
});
Thanks to skafandri
Note: make sure your id is different for each field
Excellent answer by skafandri +1
This is just updated to check for hasDatepicker class.
$('body').on('focus',".datepicker", function(){
if( $(this).hasClass('hasDatepicker') === false ) {
$(this).datepicker();
}
});
Make sure your element with the .date-picker class does NOT already have a hasDatepicker class. If it does, even an attempt to re-initialize with $myDatepicker.datepicker(); will fail! Instead you need to do...
$myDatepicker.removeClass('hasDatepicker').datepicker();
You need to run the .datepicker(); again after you've dynamically created the other textbox elements.
I would recommend doing so in the callback method of the call that is adding the elements to the DOM.
So lets say you're using the JQuery Load method to pull the elements from a source and load them into the DOM, you would do something like this:
$('#id_of_div_youre_dynamically_adding_to').load('ajax/get_textbox', function() {
$(".datepicker_recurring_start" ).datepicker();
});
This was what worked for me (using jquery datepicker):
$('body').on('focus', '.datepicker', function() {
$(this).removeClass('hasDatepicker').datepicker();
});
The new method for dynamic elements is MutationsObserver .. The following example uses underscore.js to use ( _.each ) function.
MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
var observerjQueryPlugins = new MutationObserver(function (repeaterWrapper) {
_.each(repeaterWrapper, function (repeaterItem, index) {
var jq_nodes = $(repeaterItem.addedNodes);
jq_nodes.each(function () {
// Date Picker
$(this).parents('.current-repeateritem-container').find('.element-datepicker').datepicker({
dateFormat: "dd MM, yy",
showAnim: "slideDown",
changeMonth: true,
numberOfMonths: 1
});
});
});
});
observerjQueryPlugins.observe(document, {
childList: true,
subtree: true,
attributes: false,
characterData: false
});
$('body').on('focus',".my_date_picker", function(){
$(this).datepicker({
minDate: new Date(),
});
});
None of the other solutions worked for me. In my app, I'm adding the date range elements to the document using jquery and then applying datepicker to them. So none of the event solutions worked for some reason.
This is what finally worked:
$(document).on('changeDate',"#elementid", function(){
alert('event fired');
});
Hope this helps someone because this set me back a bit.
you can add the class .datepicker in a javascript function, to be able to dynamically change the input type
$("#ddlDefault").addClass("datepicker");
$(".datepicker").datetimepicker({ timepicker: false, format: 'd/m/Y', });
I have modified #skafandri answer to avoid re-apply the datepicker constructor to all inputs with .datepicker_recurring_start class.
Here's the HTML:
<div id="content"></div>
<button id="cmd">add a datepicker</button>
Here's the JS:
$('#cmd').click(function() {
var new_datepicker = $('<input type="text">').datepicker();
$('#content').append('<br>a datepicker ').append(new_datepicker);
});
here's a working demo
This is what worked for me on JQuery 1.3 and is showing on the first click/focus
function vincularDatePickers() {
$('.mostrar_calendario').live('click', function () {
$(this).datepicker({ showButtonPanel: true, changeMonth: true, changeYear: true, showOn: 'focus' }).focus();
});
}
this needs that your input have the class 'mostrar_calendario'
Live is for JQuery 1.3+ for newer versions you need to adapt this to "on"
See more about the difference here http://api.jquery.com/live/
$( ".datepicker_recurring_start" ).each(function(){
$(this).datepicker({
dateFormat:"dd/mm/yy",
yearRange: '2000:2012',
changeYear: true,
changeMonth: true
});
});

Bootstrap 3 Datepicker v4: dp.show and dp.change events are not fired when datepicker is inline

I'm using the 4.17.37 of Bootstrap 3 Datepicker - eonasdan datepicker
I have an inline datepicker correctly showed and I would only the days mode, so I use the following code, but the events dp.show and dp.update are not fired.
$('#datetimepicker').datetimepicker({
inline: true,
format: 'DD/MM/YYYY'
}).on('dp.show dp.update', function () {
$(".datepicker-days").find("th").eq(1).removeAttr('title')
.css('cursor', 'default')
.css('background', 'inherit').on('click', function (e) {
e.stopPropagation();
});
});
EDIT 1
I tried also with dp.change (and show.dp, update.dp, change.dp too).
If the datepicker is not inline the events are fired.
EDIT 2
I'm using:
jquery-1.12.3.min.js
moment.js/2.13.0/moment.min.js
moment.js/2.13.0/moment-with-locales.min.js
bootstrap/3.3.6/js/bootstrap.min.js
bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js
EDIT 3
The same issue with version 4.17.42
The issue is that the dp.show event doesn't trigger when the widget is inline.
According to plugin documentation, the dp.show event is only emitted from toggle() or show() functions, but only if the widget was hidden before the call.
So my solution is a little bit dirty, but I think that it solves your problem. You can call hide() and show() functions immediately after widget initialization.
$('#datetimepicker').datetimepicker({
inline: true,
format: 'DD/MM/YYYY'
}).on('dp.show dp.change', function () {
// console.log('dp.show or dp.change event');
$(".datepicker-days").find("th").eq(1)
.removeAttr('title')
.css('cursor', 'default')
.css('background', 'inherit')
.on('click', function (e) {
e.stopPropagation();
});
});
$('#datetimepicker').data("DateTimePicker").hide();
$('#datetimepicker').data("DateTimePicker").show();
Fiddle here: https://jsfiddle.net/zeudzqe1/.
Any further improvement of this response is welcomed.
Have you tried dp.change ? (instead of dp.show)
$('#datetimepicker').datetimepicker({
inline: true,
format: 'DD/MM/YYYY'
}).on('dp.change dp.update', function () {
$(".datepicker-days").find("th").eq(1).removeAttr('title')
.css('cursor', 'default')
.css('background', 'inherit').on('click', function (e) {
e.stopPropagation();
});
});
The plugin insists that the component is placed within a relatively positioned container.
It actually checks, and throws an error if needed:
datetimepicker component should be placed within a relative positioned container
Uncaught errors cause it to abandon the rest of the code, by design.
I fixed it by making the parent relatively positioned:
JS
// no changes!
$('#datetimepicker').datetimepicker({
inline: true,
format: 'DD/MM/YYYY'
}).on('dp.show dp.update', function () {
$(".datepicker-days").find("th").eq(1).removeAttr('title')
.css('cursor', 'default')
.css('background', 'inherit').on('click', function (e) {
e.stopPropagation();
});
});
CSS
.relatively-positioned {
position: relative;
}
HTML
<div class="relatively-positioned">
<input id="datetimepicker">
</div>

Jquery datepicker change event trigger and input's default change event

I have datepicker
<input type='text' class='inp'>
<script>
$('.inp').datepicker();
$(".inp").on("change",function (){
console.log('inp changed');
});
</script>
When I first change '.inp' manually type there a value, then immediately I click on datepicker's opened calendar. I get two 'change' event listeners. First from manual change, then from datepicker change.
How can I avoid this?
Set your input readOnly, it will help you to change the value of field through icon only.
<input type='text' class='inp' readOnly />
then use onSelect to get selected date, as following:
$(function() {
$(".inp").datepicker({
onSelect: function(dateText, inst) {
// alert(dateText);
}
});
});
Try using the onSelect function like:
$(function() {
$( ".datepicker" ).datepicker({
onSelect: function() {
//your code here
}});
This will be fired when they select a date from the calendar not when they are typing.
You can have onSelect trigger the change event on the text field. This way editing the date via the text box or via the date picker behave the same.
$('.inp').datepicker({
onSelect: function() {
return $(this).trigger('change');
}
});
$(".inp").on("change",function (){
console.log('inp changed');
});
If you are using the bootstrap datepicker you can do the following:
$('.datepicker').datepicker()
.on('changeDate', function(e){
# `e` here contains the extra attributes
});
For more details view: Bootstrap Datepicker events
Thanks! Everybody, but I could not make field readonly one, this is requirement. So I had to reasearch myself. So I posting my final solution. I did unbinding for 150 ms, then bind again.
I made a jquery plugin for this
function myfunc(that){
$(that).one('change', function(){
var that = this;
setTimeout(function(){myfunc(that);}, 150);
//some logic
}
)
}
myfunc(".inp");
Thank you everyone, this is what I used though,
function myfunction(x,x2){
var date1 = new Date(x);
var MyDateString;
MyDateString = date1.getFullYear()+ '/' + ('0' + (date1.getMonth()+1)).slice(-2) + '/' + ('0' + date1.getDate()).slice(-2);
x2.value= MyDateString;
}
x, being the datepicker value and x2 being the datepicker object
Try this
$(function() {
$("#birth_date").datepicker({
onSelect: function() {
console.log("You Code Here");
}});
});
If you are using datepiker ui you can also used following formate
<input type='text' class='inp'>
<script>
$('.inp').datepicker({
onSelect: function(date) {
$(this).change();
},
}).on("change",function (){
console.log('inp changed');
});
</script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" type="text/css"/>
<script src="js/jquery-1.12.4.js"></script>
<script src="js/jquery-ui.js"></script>
<script>
var j = jQuery.noConflict();
j(function() {
j("#datepickerFrom").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: "yy/mm/dd",
onSelect: function () {
var date = $(this.value).selector;
document.getElementById("dateFrom").value = date;
},
}).on("change",function (){
var date = $(this.value).selector;
document.getElementById("dateFrom").value = date;
})
.datepicker("setDate",document.getElementById("dateFrom").value);
});
</script>
<input id="datepickerFrom"/>
<input type="hidden" name="dateFrom" id="dateFrom"/>
if you are using date picker of jquery there is no need of calender event fire.
you can fire the event on textbox "textchanged"

jquery datepicker - show week number if has specific class

I am using the jquery ui datepicker but I want to show the week number only if the input element has a specific class...
Here's what I've tried but with no success...
$(".myCal").datepicker({
showWeek: function(dateText, inst) { $(this).hasClass("showWeek"); }
});
As class selector is used, each method is required to iterate over all matching elements and then use $(this).
$(".myCal").each(function () {
$(this).datepicker({
showWeek: $(this).hasClass('showWeek')
});
});
http://jsfiddle.net/Ubw3L/5/
Can you try this
$(".myCal").datepicker({
showWeek: $(this).hasClass("showWeek");
});
As the API states, showWeek accept boolean value.
$('.myCal').each(function () {
$(this).datepicker({
showWeek: $(this).hasClass('showWeek');
});
});

putting datepicker() on dynamically created elements - JQuery/JQueryUI

I have dynamically created textboxes, and I want each of them to be able to display a calendar on click. The code I am using is:
$(".datepicker_recurring_start" ).datepicker();
Which will only work on the first textbox, even though all my textboxes have a class called datepicker_recurring_start.
Your help is much appreciated!
here is the trick:
$('body').on('focus',".datepicker_recurring_start", function(){
$(this).datepicker();
});​
DEMO
The $('...selector..').on('..event..', '...another-selector...', ...callback...); syntax means:
Add a listener to ...selector.. (the body in our example) for the event ..event.. ('focus' in our example). For all the descendants of the matching nodes that matches the selector ...another-selector... (.datepicker_recurring_start in our example) , apply the event handler ...callback... (the inline function in our example)
See http://api.jquery.com/on/ and especially the section about "delegated events"
For me below jquery worked:
changing "body" to document
$(document).on('focus',".datepicker_recurring_start", function(){
$(this).datepicker();
});
Thanks to skafandri
Note: make sure your id is different for each field
Excellent answer by skafandri +1
This is just updated to check for hasDatepicker class.
$('body').on('focus',".datepicker", function(){
if( $(this).hasClass('hasDatepicker') === false ) {
$(this).datepicker();
}
});
Make sure your element with the .date-picker class does NOT already have a hasDatepicker class. If it does, even an attempt to re-initialize with $myDatepicker.datepicker(); will fail! Instead you need to do...
$myDatepicker.removeClass('hasDatepicker').datepicker();
You need to run the .datepicker(); again after you've dynamically created the other textbox elements.
I would recommend doing so in the callback method of the call that is adding the elements to the DOM.
So lets say you're using the JQuery Load method to pull the elements from a source and load them into the DOM, you would do something like this:
$('#id_of_div_youre_dynamically_adding_to').load('ajax/get_textbox', function() {
$(".datepicker_recurring_start" ).datepicker();
});
This was what worked for me (using jquery datepicker):
$('body').on('focus', '.datepicker', function() {
$(this).removeClass('hasDatepicker').datepicker();
});
The new method for dynamic elements is MutationsObserver .. The following example uses underscore.js to use ( _.each ) function.
MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
var observerjQueryPlugins = new MutationObserver(function (repeaterWrapper) {
_.each(repeaterWrapper, function (repeaterItem, index) {
var jq_nodes = $(repeaterItem.addedNodes);
jq_nodes.each(function () {
// Date Picker
$(this).parents('.current-repeateritem-container').find('.element-datepicker').datepicker({
dateFormat: "dd MM, yy",
showAnim: "slideDown",
changeMonth: true,
numberOfMonths: 1
});
});
});
});
observerjQueryPlugins.observe(document, {
childList: true,
subtree: true,
attributes: false,
characterData: false
});
$('body').on('focus',".my_date_picker", function(){
$(this).datepicker({
minDate: new Date(),
});
});
None of the other solutions worked for me. In my app, I'm adding the date range elements to the document using jquery and then applying datepicker to them. So none of the event solutions worked for some reason.
This is what finally worked:
$(document).on('changeDate',"#elementid", function(){
alert('event fired');
});
Hope this helps someone because this set me back a bit.
you can add the class .datepicker in a javascript function, to be able to dynamically change the input type
$("#ddlDefault").addClass("datepicker");
$(".datepicker").datetimepicker({ timepicker: false, format: 'd/m/Y', });
I have modified #skafandri answer to avoid re-apply the datepicker constructor to all inputs with .datepicker_recurring_start class.
Here's the HTML:
<div id="content"></div>
<button id="cmd">add a datepicker</button>
Here's the JS:
$('#cmd').click(function() {
var new_datepicker = $('<input type="text">').datepicker();
$('#content').append('<br>a datepicker ').append(new_datepicker);
});
here's a working demo
This is what worked for me on JQuery 1.3 and is showing on the first click/focus
function vincularDatePickers() {
$('.mostrar_calendario').live('click', function () {
$(this).datepicker({ showButtonPanel: true, changeMonth: true, changeYear: true, showOn: 'focus' }).focus();
});
}
this needs that your input have the class 'mostrar_calendario'
Live is for JQuery 1.3+ for newer versions you need to adapt this to "on"
See more about the difference here http://api.jquery.com/live/
$( ".datepicker_recurring_start" ).each(function(){
$(this).datepicker({
dateFormat:"dd/mm/yy",
yearRange: '2000:2012',
changeYear: true,
changeMonth: true
});
});

Categories