Real World Scenario: Month Based Selection using AJAX Calendar Extender

Often we get requirement of enabling only month based selection in calendar control in which a calendar should display only month instead of dates or you can say a calendar that allow users to pick month only. This can be achieved by manipulating functionality of AJAX Calendar extender using JavaScript.

First, you need to set the behaviorID property of Calendar extender control and add two event handler “OnClientHidden” and “OnClientShown”. For instance,

<asp:TextBox ID="txtDate" runat="server" ReadOnly="false" onfocus="AjaxDateOnFocus(this);" Width="60px" onblur="AjaxDateOnBlur(this);" />
<
cc1:CalendarExtender ID="ctxtDate" runat="server" TargetControlID="txtDate" Format="MMM-yyyy" OnClientHidden="onCalendarHidden" OnClientShown="onCalendarShown" BehaviorID="calendar1" />

Now use the following JavaScript with respective BehaviorID

function onCalendarShown() {
var cal = $find("calendar1"); //Setting the default mode to month
cal._switchMode("months", true); //Iterate every month Item and attach click event to it
if (cal._monthsBody) {
for (var i = 0; i < cal._monthsBody.rows.length; i++) {
var row = cal._monthsBody.rows[i];
for (var j = 0; j < row.cells.length; j++) {
Sys.UI.DomEvent.addHandler(row.cells[j].firstChild, "click", call);
}
}
}
}

function onCalendarHidden() {
var cal = $find("calendar1");
//Iterate every month Item and remove click event from it
if (cal._monthsBody) {
for (var i = 0; i < cal._monthsBody.rows.length; i++) {
var row = cal._monthsBody.rows[i];
for (var j = 0; j < row.cells.length; j++) {
Sys.UI.DomEvent.removeHandler(row.cells[j].firstChild, "click", call);
}
}
}
}

function call(eventElement) {
var target = eventElement.target;
switch (target.mode) {
case "month":
var cal = $find("calendar1");
cal._visibleDate = target.date;
cal.set_selectedDate(target.date);
cal._switchMonth(target.date);
cal._blur.post(true);
cal.raiseDateSelectionChanged();
break;
}
}

That’s all 🙂 and your calendar extender will now look like

image

Enjoy!

Please note that the script is partially taken from AghaUsman.net

  • Hi.
    What version of the Ajax Toolkit are you using please?
    My page isn’t happy with the calls to AjaxDateOnFocus and AjaxDateOnBlur. 🙁

  • Hi Richard,
    This works in Ajax Toolkit 3.*, please check for any reference is missing. I have not tested in 4.0.

  • Excellent info bai..