Saturday, March 19, 2011

JQuery UI: Datepicker with Month and Year only

This can be done by hiding the calendar via some CSS trick:

$(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('yy-mm', new Date(year, month, 1)));
}
});
$(".monthPicker").focus(function () {
$(".ui-datepicker-calendar").hide();
$("#ui-datepicker-div").position({
my: "center top",
at: "center bottom",
of: $(this)
});
});
});
view raw gistfile1.js hosted with ❤ by GitHub
<label for="month">Month: </label>
<input type="text" id="month" name="month" class="monthPicker" />
view raw gistfile2.html hosted with ❤ by GitHub

4 comments:

  1. Anonymous9:50 PM

    Good post !
    I made a small modification on the onClose function to be more generic, so it can be used on multiple inputs with different dateFormat.

    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));
    $(this).datepicker('refresh');
    }

    ReplyDelete
  2. give me demo option

    ReplyDelete
  3. How do I only have years selection from date picker

    ReplyDelete
  4. It would be very helpfull if you had placed a picture of the final result of the datepicker, so we shouldn't need to test it by ourselves to decide if we'll use or not the approach.

    ReplyDelete