jQuery UI DatePicker to show month year only

665,273

Solution 1

Here's a hack (updated with entire .html file):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
    <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
    <script type="text/javascript">
        $(function() {
            $('.date-picker').datepicker( {
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            dateFormat: 'MM yy',
            onClose: function(dateText, inst) { 
                $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
            }
            });
        });
    </script>
    <style>
    .ui-datepicker-calendar {
        display: none;
    }
    </style>
</head>
<body>
    <label for="startDate">Date :</label>
    <input name="startDate" id="startDate" class="date-picker" />
</body>
</html>

EDIT jsfiddle for the above example: http://jsfiddle.net/DBpJe/7755/

EDIT 2 Adds the month year value to input box only on clicking of Done button. Also allows to delete input box values, which isn't possible in above field http://jsfiddle.net/DBpJe/5103/

EDIT 3 updated Better Solution based on rexwolf's solution down.
http://jsfiddle.net/DBpJe/5106

Solution 2

This code is working flawlessly to me:

<script type="text/javascript">
$(document).ready(function()
{   
    $(".monthPicker").datepicker({
        dateFormat: 'MM yy',
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,

        onClose: function(dateText, inst) {
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).val($.datepicker.formatDate('MM yy', new Date(year, month, 1)));
        }
    });

    $(".monthPicker").focus(function () {
        $(".ui-datepicker-calendar").hide();
        $("#ui-datepicker-div").position({
            my: "center top",
            at: "center bottom",
            of: $(this)
        });
    });
});
</script>

<label for="month">Month: </label>
<input type="text" id="month" name="month" class="monthPicker" />

Output is:

enter image description here

Solution 3

@Ben Koehler, that's prefect! I made a minor modification so that using a single instance of the date picker more than once works as expected. Without this modification the date is parsed incorrectly and the previously selected date is not highlighted.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
    <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
    <script type="text/javascript">
    $(function() {
        $('.date-picker').datepicker( {
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            dateFormat: 'MM yy',
            onClose: function(dateText, inst) { 
                var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                $(this).datepicker('setDate', new Date(year, month, 1));
            },
            beforeShow : function(input, inst) {
                var datestr;
                if ((datestr = $(this).val()).length > 0) {
                    year = datestr.substring(datestr.length-4, datestr.length);
                    month = jQuery.inArray(datestr.substring(0, datestr.length-5), $(this).datepicker('option', 'monthNamesShort'));
                    $(this).datepicker('option', 'defaultDate', new Date(year, month, 1));
                    $(this).datepicker('setDate', new Date(year, month, 1));
                }
            }
        });
    });
    </script>
    <style>
    .ui-datepicker-calendar {
        display: none;
        }
    </style>
</head>
<body>
    <label for="startDate">Date :</label>
    <input name="startDate" id="startDate" class="date-picker" />
</body>
</html>

Solution 4

The above answers are pretty good. My only complaint is that you can't clear the value once it's been set. Also I prefer the extend-jquery-like-a-plugin approach.

This works perfect for me:

$.fn.monthYearPicker = function(options) {
    options = $.extend({
        dateFormat: "MM yy",
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        showAnim: ""
    }, options);
    function hideDaysFromCalendar() {
        var thisCalendar = $(this);
        $('.ui-datepicker-calendar').detach();
        // Also fix the click event on the Done button.
        $('.ui-datepicker-close').unbind("click").click(function() {
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            thisCalendar.datepicker('setDate', new Date(year, month, 1));
        });
    }
    $(this).datepicker(options).focus(hideDaysFromCalendar);
}

Then invoke like so:

$('input.monthYearPicker').monthYearPicker();

Solution 5

<style>
.ui-datepicker table{
    display: none;
}

<script type="text/javascript">
$(function() {
    $( "#manad" ).datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'yy-mm',
        onClose: function(dateText, inst) { 
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));
        },
        beforeShow : function(input, inst) {
            if ((datestr = $(this).val()).length > 0) {
                actDate = datestr.split('-');
                year = actDate[0];
                month = actDate[1]-1;
                $(this).datepicker('option', 'defaultDate', new Date(year, month));
                $(this).datepicker('setDate', new Date(year, month));
            }
        }
    });
});

This will solve the problem =) But I wanted the timeFormat yyyy-mm

Only tried in FF4 though

Share:
665,273
Aanu
Author by

Aanu

Updated on July 08, 2022

Comments

  • Aanu
    Aanu almost 2 years

    I am using jQuery date picker to display the calendar all over my app. I want to know if I can use it to display the month and year (May 2010) and not the calendar?

  • Reigel Gallarde
    Reigel Gallarde about 14 years
    I think you are not reading the question. Aanu wants to "display the month and year (May 2010) and not the calendar".
  • Aanu
    Aanu about 14 years
    As I am already using jquery datepicker, I prefer to use it or construct the month and year manually.
  • Aanu
    Aanu about 14 years
    This didn't work. This one shows the calendar. whereas I just want the month and year list boxes and not the actual calendar with dates.
  • Ami Gulzadi
    Ami Gulzadi about 13 years
    Calling 'setDate' will reopen the picker in some browsers. To prevent this, disabled and enabled the picker: $(this).datepicker('disable'); $(this).datepicker('setDate', new Date(year1, month1, 1)); $(this).datepicker('enable');
  • ThiamTeck
    ThiamTeck about 13 years
    @Sven here is an alternative: $(this).val($.datepicker.formatDate('MM yy', new Date(year, month, 1)));
  • Paweł Dyda
    Paweł Dyda almost 13 years
    "yy" in JQuery is four digit year. If this is what you want, you have just achieved that.
  • Tom Van Schoor
    Tom Van Schoor almost 13 years
    $(this).datepicker('disable'); $(this).datepicker('setDate', new Date(year, month, 1)); $(this).datepicker('enable'); Solves the problem.
  • supertopi
    supertopi over 12 years
    I'm trying to use this solution, but using getDate on a datepicker returns only today. What's up?
  • poweratom
    poweratom over 12 years
    I see most examples are using inline styles on the page itself. This would be a problem if somehow you need more than one calendars (each with different settings, for example) on the same page. I prefer adding styles in the .css file as such: #ui-datepicker-div.noCalendar .ui-datepicker-calendar, #ui-datepicker-div.noCalendar .ui-datepicker-header a {display: none;} #ui-datepicker-div.noCalendar .ui-datepicker-header .ui-datepicker-title{width: 100%; margin: 0;} And then use Javascript to manipulate the behavior: $("#ui-datepicker-div").addClass('noCalendar');
  • denis.peplin
    denis.peplin over 10 years
    Not maintained, but there is a fork: github.com/zorab47/jquery.ui.monthpicker
  • knocte
    knocte over 9 years
    in the end I'm downvoting this because it is unworkable, as the onSelect and/or onChangeMonthYear and/or onClose events either don't fire, or don't receive the correct values, or, if overriden, make the widget stop working
  • Parag
    Parag about 9 years
    JUst add this line to beforeShow:{ inst.dpDiv.addClass('month_year_datepicker') }. the dates flashing will stop :). Also i think .focus wont be needed then
  • Bik
    Bik about 9 years
    On the above example If i want to clear the text box then i can't. Can anyone help me.
  • Johnny Bigoode
    Johnny Bigoode over 7 years
    Just and FYI. The line 'inst.dpDiv.addClass('datepicker-month-year');' will add the whole month-year to the calendar div of datepicker, meaning, if there are other date fields with datepicker, they will stop working because of that. Since there's only a single div for the calendar, it'd be interesting to add a '$('.datepicker-month-year').removeClass('datepicker-month-y‌​ear');' using the beforeShow onto any other datepickers that require the tradicional calendar. OR, remove the class when you lose focus. But I couldn't find anything related to that in the api
  • Pang
    Pang over 7 years
    Link is dead. This site can’t be reached | lucianocosta.info’s server DNS address could not be found.
  • Sebastian S.
    Sebastian S. over 7 years
  • Alex F
    Alex F over 6 years
    This is the full answer everyone should be using. Biggest problem solved for me was date entry popup always defaults to current month and year, regardless of what's already in it. This answer fixed it.
  • Riya
    Riya over 4 years
    @stackoverflow.com/users/11996/ben-koehler, how to display the current month and year on that textbox as default value, on page load?
  • Ben Koehler
    Ben Koehler over 4 years
    @Riya, Check this answer out to set the default value: stackoverflow.com/a/17492468/11996. You only need to add .datepicker("setDate", new Date()); to the end of the initialization call.
  • Chazaq
    Chazaq over 4 years
    This answer is mostly correct. However, I had to change MM to M to get the correct month to be selected when a date is already selected.
  • Alfiza malek
    Alfiza malek about 4 years
    How can one set value to this calendar.
  • nasch
    nasch almost 4 years
    Updated link is also broken.
  • Ultroman the Tacoman
    Ultroman the Tacoman over 2 years
    Very neat solution! But if I click to open the picker, then write a wrongly formatted date in the field while it is open, and then close the picker, the wrongly formatted text stays. You can see the onClose in my version, for an example on how to handle that edge-case. There are many edge-cases with these :)
  • Ultroman the Tacoman
    Ultroman the Tacoman over 2 years
    If I click to open the picker, then write a wrongly formatted date in the field while it is open, and then close the picker, the wrongly formatted text stays. You can see the onClose in my version for an example on how to handle that edge-case. There are many edge-cases with these :)
  • Ultroman the Tacoman
    Ultroman the Tacoman over 2 years
    Only works with one date format. You have to fix the substringing for each instance with a different format. And if I click to open the picker, then write a wrongly formatted date in the field while it is open, and then close the picker, the wrongly formatted text stays. You can see the onClose in my version, for an example on how to handle that edge-case. There are many edge-cases with these :)
  • adam
    adam over 2 years
    This answer really helped me thanks a lot since I use M format
  • user9437856
    user9437856 over 2 years
    Thank you it's working for me.