반응형

jquery datepicker를 이용해서 년월만 선택하고 싶을 때가 있다.
이때 유용하게 사용할 수 있는 방법이다.
활용성을 높이기 위해 공통 js파일에 show_calendar_month라는 Function을 정의해서 사용했다. 이렇게 이용을 하면 사용하고자 하는 페이지에서 보다 유연하게 사용할 수 있다.
input 파라미터로는 선택한 년월을 표기할 textbox의 id를 넣어 주면 된다.
년월 picker 기능은 모두 Function에 정의해 두고 호출만 하면 된다.

function show_calendar_month(obj) {
	$("#" + obj).datepicker({
		monthNames: [ "1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월" ],
		monthNamesShort: [ "1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월" ],
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'yy-mm',
        onChangeMonthYear: function (year, month, inst) {
        	$(this).val($.datepicker.formatDate('yy-mm', new Date(year, month - 1, 1)));
    	},
        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));
            }
        }
    });
    
    $("#" + obj).focus(function () {
        $(".ui-datepicker-calendar").hide();
    });
    
    $('#' + obj).datepicker('show');
}

이렇게 정의한 Function을 html/jsp 파일에서 아래와 같이 호출만 하면 된다.

...
<td class="c" width="250px">
	<input type=text id="Fdate1" name="Fdate1" value='<cnsone:date value="${Fdate1}"/>' readonly style="width:70px;text-align:center;">
	<input type='button' onClick="show_calendar_month('Fdate1');" style="background:url(${WEBROOT}/images/icon/calendar.gif);border:0;width:16px;height:18px;cursor:hand;vertical-align:middle;">
</td>
...

스타일 시트를 추가해서 기존에 보이던 일자를 보이지 않도록 처리한다.
<style>
table.ui-datepicker-calendar { display:none; }
</style>
달력 아이콘 버튼을 클릭하면 아래의 이미지와 같이 년월 picker의 모습을 보게 된다.
년과 월만을 선택하는 UI를 datepicker를 이용해서 간단하게 만들 수 있다.

그림1 - 년월 Picker
반응형

+ Recent posts