셀렉트박스: 1. 수지구 2. 기흥구 3. 처인구
셀렉트박스에 선택한 구에 있는 동을 보여주는 코드를 작성하고자 한다.
<script type="text/javascript">
//미리 동 정보를 입력해둔다.
var suzi=['풍덕천동','신봉동','죽전동','동천동','고기동','상현동','성복동'];
var giheung=['신갈동','영덕동','하갈동','구갈동','상갈동','보라동',
'지곡동','공세동','고매동','농서동','서천동','언남동','청덕동',
'마북동','동백동','중동','상하동','보정동'];
var cheoin=['포곡읍','모현읍','이동읍','남사읍','원삼면',
'백암면','양지면','중앙동','역북동','삼가동','유림동'];
var value;
function handleOnChange(e) {
//기존 동 모두 지우기
var locations=document.getElementById("locations");
while (locations.hasChildNodes())
{
locations.removeChild(locations.firstChild );
}
//selected 구 가져오기
value = e.value;
var selectedList;
if(value=="suzi")
selectedList=suzi;
else if(value=="giheung")
selectedList=giheung;
else
selectedList=cheoin;
//동적으로 div 생성
for(var i=0;i<selectedList.length;i++)
{
const newDiv = document.createElement('div');
document.getElementById("locations").appendChild(newDiv);
newDiv.innerText=selectedList[i];
}
}
</script>
<body>
<div class="select-box">
<select name="gu" onchange="handleOnChange(this)">
<option value="suzi">수지구</option>
<option value="giheung">기흥구</option>
<option value="cheoin">처인구</option>
</select>
</div>
<div class="location-box">
<div id="locations">
<!--이곳에 div 생성된다-->
</div>
</div>
</body>