I want to get the month for the current active month in the calendar. For example, the current month (December 2012) includes (but does not show) Nov 26-30, which the beforeShowDay
(date) function includes when looping in the 'date'. I want to get Dec '11' (0 based index) at the start but can't find how to get this.
Using date.getMonth() + 1
doesn't work as it first gives me Novembers month number but I want Dec as that is the selected month in the calendar. I get Dec when I eventually get to in in the loop via 'date' but it's to late at that point.
Any ideas how to get this?
var datePicker = $('#datepicker')
datePicker.datepicker();
var date = datePicker.datepicker('getDate');
alert(date.getMonth())
Will output 11 (currently), although this will only work once the calendar date picker has been initialized, or shown. This means if you use the markup from the docs (the input field) you'll get no alert. A workaround for this could be setting the datepicker to a div surrounding the input, and triggering the datepicker show/hide when the input gains or loses focus.
Something on the lines of this fiddle. It's a bit ugly but it should serve as a workaround for the input part:
var datePicker = $('#datepicker')
datePicker.datepicker();
datePicker.hide();
var date = datePicker.datepicker('getDate');
alert(date.getMonth());
$("[rel='#datepicker']").focus(function(){
datePicker.show();
});
$("[rel='#datepicker']").blur(function(){
datePicker.hide();
});
With the following HTML:
<input rel='#datepicker' type='text'/>
<div id='datepicker'></div>
Update
You also ask how to get the month for the calendar on the beforeShow
method. The way I think of it, you have two alternatives. Either you've set the month overriding the defaultMonth
option or it will be the current month. If you've set it manually, you already have it, if you didn't it will probably just be the same number as in new Date().getMonth()
(which in this case is, as you've probably guessed, 11)
If I understood you correctly, this is what you are looking for: http://jsfiddle.net/kACfV/
// Initially, set current date as the active month.
var activeMonth = new Date().getMonth() + 1;
$(function() {
$("#datepicker").datepicker({
// This is run before beforeShowDay(date).
onChangeMonthYear: function (year, month, inst) {
activeMonth = month; // Store active month when month is changed.
},
beforeShowDay: function (date) {
// Do your logic here with activeMonth.
console.log(date + " > " + activeMonth);
return [true, ""]
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With