show only month and year in ajax toolkit calendar extender

sephtian picture sephtian · May 22, 2013 · Viewed 30.4k times · Source

please help.. how to modify calendar extender display in ajax calendar extender to show only month and year, i mean the calendar view NOT the textbox text format, so i only select month name in specific year.

Answer

Adam picture Adam · Jan 7, 2014

The OnClientShown function shown needs to do more than just switch modes. Here is the solution I got working, where it only shows the months and you can select the month and have only the month and year shown in the textbox.

Step 1

<asp:CalendarExtender ID="calendar1" ClientIDMode="Static" runat="server"
                      TargetControlID="txtDate" Format="yyyy-MM" 
                      DefaultView="Months" OnClientShown="onCalendarShown"
                      OnClientHidden="onCalendarHidden" PopupButtonID="imgStart" />

Please note: ClientIDMode = Static, DefaultView = Months and OnClientShown and OnClientHidden events attached.

You can also change Format="yyyy-MM" to whatever format you want with the month and year in it.

Step 2

Create these Javascript functions. If you don't have JQuery loaded, change $find to document.getElementById

<script type="text/javascript">

    function onCalendarHidden() {
        var cal = $find("calendar1");

        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 onCalendarShown() {

        var cal = $find("calendar1");

        cal._switchMode("months", true);

        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 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;
        }
    }
</script>

Code modified from: http://danajaatcse.wordpress.com/2010/06/14/modifying-a-ajax-calender-control-to-operate-with-only-years/