자바스크립트로 주간(일~토) 셀렉트 박스 만들기

년도와 월을 선택하면 해당 년/월에 포함 되어있는 주 시작일과 종료일을 셀렉트박스로 만들게 하는 함수 입니다.

2013-08-20_011738

요령 모양의 셀렉트 박스 입니다. 작동되는 모습은 예제링크를 통해서 확인해주세요.

예제링크

function makeWeekSelectOptions() {
	var year = $("#sh_year").val();
	var month = $("#sh_month").val();

	var today = new Date();

	var sdate = new Date(year, month-1, 01);
	var lastDay = (new Date(sdate.getFullYear(), sdate.getMonth()+1, 0)).getDate();
	var endDate = new Date(sdate.getFullYear(), sdate.getMonth(), lastDay);

	var week = sdate.getDay();
	sdate.setDate(sdate.getDate() - week);
	var edate = new Date(sdate.getFullYear(), sdate.getMonth(), sdate.getDate());

	var obj = document.getElementById("sh_week");
	obj.options.length = 0;
	var seled = "";
	while(endDate.getTime() >= edate.getTime()) {

		var sYear = sdate.getFullYear();
		var sMonth = (sdate.getMonth()+1);
		var sDay = sdate.getDate();

		sMonth = (sMonth < 10) ? "0"+sMonth : sMonth;
		sDay = (sDay < 10) ? "0"+sDay : sDay;

		var stxt = sYear + "-" + sMonth + "-" + sDay;

		edate.setDate(sdate.getDate() + 6);

		var eYear = edate.getFullYear();
		var eMonth = (edate.getMonth()+1);
		var eDay = edate.getDate();

		eMonth = (eMonth < 10) ? "0"+eMonth : eMonth;
		eDay = (eDay < 10) ? "0"+eDay : eDay;

		var etxt = eYear + "-" + eMonth + "-" + eDay;

		if(today.getTime() >= sdate.getTime() && today.getTime() <= edate.getTime()) {
			seled = stxt+"|"+etxt;
		}

		obj.options[obj.options.length] = new Option(stxt+"~"+etxt, stxt+"|"+etxt);

		sdate = new Date(edate.getFullYear(), edate.getMonth(), edate.getDate() + 1);
		edate = new Date(sdate.getFullYear(), sdate.getMonth(), sdate.getDate());
	}

	if(seled) obj.value = seled;
}
<select name="sh_year" id="sh_year" onchange="makeWeekSelectOptions();">
<option value='2013' selected='selected'>2013년</option>
</select>

<select name="sh_month" id="sh_month" onchange="makeWeekSelectOptions();">
<option value='01'>01월</option>
<option value='02'>02월</option>
<option value='03'>03월</option>
<option value='04'>04월</option>
<option value='05'>05월</option>
<option value='06'>06월</option>
<option value='07'>07월</option>
<option value='08' selected='selected'>08월</option>
<option value='09'>09월</option>
<option value='10'>10월</option>
<option value='11'>11월</option>
<option value='12'>12월</option>
</select>

<select name="sh_week" id="sh_week">
</select>

 

 

CC BY-NC-SA 4.0 This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.