Add a monthly datepicker with jQuery - modification

This is how you can add a monthly datepicker modification in jQuery in Drupal and use numeric date format like yyyymm.

This version uses the format of yyyymm e.g. '201112' for Dec 2011

You have to add a class to your style sheet, hiding the calendar table. This way to solve the problem has a negative thing, it is not possible to clear the field and leave it blank if you once enter a value or click in the field. The reason is that onClose hook was used to fill in value and it is triggered every time the datepicker field is closed. Another script that requires to download a new script solves this problem and I think it is a better solution, see below.

.my-month-select .ui-datepicker-calendar {
display: none;
}

<?php

    $script
.= "$(function() {
                    $('.add-datepicker-y-m').datepicker( {
                        changeMonth: true,
                        showWeek: true,
                        changeYear: true,
                        showButtonPanel: true,
                        dateFormat: 'yymm',
                        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));
                            $('#ui-datepicker-div').removeClass('my-month-select');
                        },
                        beforeShow : function(input, inst) {
                            if ((datestr = $(this).val()).length > 0) {
                                year = datestr.substring(0, 4);
                                month = datestr.substring(4, 6)-1;
                                $(this).datepicker('option', 'defaultDate', new Date(year, month, 1));
                                $(this).datepicker('setDate', new Date(year, month, 1));
                            }
                           
                            $(document).ready(function() {
                              $('#ui-datepicker-div').addClass('my-month-select');
                            });
                           
                           
                        
                        }
                    });
                   
                });
                "
;
   
   
drupal_add_js($script, 'inline', 'footer');
?>

A modification of: http://stackoverflow.com/questions/2208480/jquery-date-picker-to-show-mo...

Knowledge keywords: