HomeCoding & Programming

jQuery datepicker to show month and year only

Like Tweet Pin it Share Share Email

jquery datepicker to show month year only

 

jQuery has very nice Date Picker library, but it can’t be customized to remove the date part, i.e. to show month and year only.
In some cases, you only need that the user selects the month and year mm/yyyy (month/year) as input without the day (like in credit card expiry date).Below is the code to show only the header of date picker with month and year selects(date will not show any more).

 

If you use this one, you have partially done but it create some confusion to user as it shows date as well and user have to select a date whereas it use only month and date.

 

$("#datepicker").datepicker({dateFormat: "mm/yy" });

For removing this confusion and hiding the date section completely, you can use the below code.

<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() {
$('#expiryDate').datepicker( {
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'mm/yy',
minDate:'m', // restrict to show month greater than current month
onClose: function(dateText, inst) {
// set the date accordingly
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) {
year = datestr.substring(datestr.length-4, datestr.length);
month = jQuery.inArray(datestr.substring(0, datestr.length-5), $(this).datepicker('option', 'monthNames'));
$(this).datepicker('option', 'defaultDate', new Date(year, month, 1));
$(this).datepicker('setDate', new Date(year, month, 1));
}
}
});
});
</script>

<style type="text/css">.ui-datepicker-calendar { display: none; }</style>

<label for="expiryDate">Expiry Date:</label>
<input name="cc_expiryDate" id="expiryDate" class="date-picker" /> (mm/yyyy)

It will show calendar likes this.

jQuery datepicker show month and year only
jQuery datepicker show month and year only