Terry Very Good

[Javascript] 다중 셀렉트 박스(chained select box) / 셀렉트 박스 2개 연동 / 시도 시군구 다중 셀렉트박스 본문

프로그래밍/(WEB) PHP & JAVASCRIPT

[Javascript] 다중 셀렉트 박스(chained select box) / 셀렉트 박스 2개 연동 / 시도 시군구 다중 셀렉트박스

테리베리 2021. 1. 27. 11:28
728x90
반응형

 

 

 

1. 기본형(걸그룹 선택 시, 다음 셀렉트박스는 해당 걸그룹 이름 보이게)

<select onchange="categoryChange(this)">
	<option>걸그룹을 선택해주세요</option>
	<option value="a">블랙핑크</option>
	<option value="b">에프엑스</option>
	<option value="c">EXID</option>
</select>

<select id="good">
<option>좋아하는 멤버를 선택해주세요</option>
</select>
<script>
function categoryChange(e) {
	var good_a = ["지수", "제니", "로제", "리사"];
	var good_b = ["빅토리아", "엠버", "루나", "크리스탈"];
	var good_c = ["LE", "하니", "정화", "혜린", "솔지"];
	var target = document.getElementById("good");

	if(e.value == "a") var d = good_a;
	else if(e.value == "b") var d = good_b;
	else if(e.value == "c") var d = good_c;

	target.options.length = 0;

	for (x in d) {
		var opt = document.createElement("option");
		opt.value = d[x];
		opt.innerHTML = d[x];
		target.appendChild(opt);
	}
}
</script>

 

 

2. 시도/시군구형(시/도 선택 시, 다음 셀렉트박스는 해당 시/도의 시/군/구 이름이 보이게)

<html>
<head>
	<title>BLUEB</title>
</head>

<body>
<script language='javascript'>
<!--
     var cnt = new Array();
     cnt[0] = new Array('전체');
     cnt[1] = new Array('전체','강남구','강동구','강북구','강서구','관악구','광진구','구로구','금천구','노원구','도봉구','동대문구','동작구','마포구','서대문구','서초구','성동구','성북구','송파구','양천구','영등포구','용산구','은평구','종로구','중구','중랑구');
     cnt[2] = new Array('전체','강서구','금정구','남구','동구','동래구','부산진구','북구','사상구','사하구','서구','수영구','연제구','영도구','중구','해운대구','기장군');
     cnt[3] = new Array('전체','남구','달서구','동구','북구','서구','수성구','중구','달성군');
     cnt[4] = new Array('전체','계양구','남구','남동구','동구','부평구','서구','연수구','중구','강화군','옹진군');
     cnt[5] = new Array('전체','광산구','남구','동구','북구','서구');
     cnt[6] = new Array('전체','대덕구','동구','서구','유성구','중구');
     cnt[7] = new Array('전체','남구','동구','북구','중구','울주군');
     cnt[8] = new Array('전체','고양시','과천시','광명시','구리시','군포시','남양주시','동두천시','부천시','성남시','수원시','시흥시','안산시','안양시','오산시','의왕시','의정부시','평택시','하남시','가평군','광주시','김포시','안성시','양주군','양평군','여주군','연천군','용인시','이천군','파주시','포천시','화성시');
     cnt[9] = new Array('전체','강릉시','동해시','삼척시','속초시','원주시','춘천시','태백시','고성군','양구군','양양군','영월군','인제군','정선군','철원군','평창군','홍천군','화천군','황성군');
     cnt[10] = new Array('전체','제천시','청주시','충주시','괴산군','단양군','보은군','영동군','옥천군','음성군','진천군','청원군');
     cnt[11] = new Array('전체','공주시','보령시','서산시','아산시','천안시','금산군','논산군','당진군','부여군','서천군','연기군','예산군','청양군','태안군','홍성군');
     cnt[12] = new Array('전체','군산시','김제시','남원시','익산시','전주시','정읍시','고창군','무주군','부안군','순창군','완주군','임실군','장수군','진안군');
     cnt[13] = new Array('전체','광양시','나주시','목포시','순천시','여수시','여천시','강진군','고흥군','곡성군','구례군','담양군','무안군','보성군','신안군','여천군','영광군','영암군','완도군','장성군','장흥군','진도군','함평군','해남군','화순군');
     cnt[14] = new Array('전체','경산시','경주시','구미시','김천시','문겅시','상주시','안동시','영주시','영천시','포항시','고령군','군위군','봉화군','성주군','영덕군','영양군','예천군','울릉군','울진군','의성군','청도군','청송군','칠곡군');
     cnt[15] = new Array('전체','거제시','김해시','마산시','밀양시','사천시','울산시','진주시','진해시','창원시','통영시','거창군','고성군','남해군','산청군','양산시','의령군','창녕군','하동군','함안군','함양군','합천군');
     cnt[16] = new Array('전체','서귀포시','제주시','남제주군','북제주군');
     function change(add) {
     sel=document.form.county
       /* 옵션메뉴삭제 */
       for (i=sel.length-1; i>=0; i--){
         sel.options[i] = null
         }
       /* 옵션박스추가 */
       for (i=0; i < cnt[add].length;i++){                     
                         sel.options[i] = new Option(cnt[add][i], cnt[add][i]);
         }         
     }
//-->
</script>
<form name=form method=post action=$PHP_SELF>
                                          시/도: 
                   <select name='city' onchange="change(this.selectedIndex);"  class=input >
                       <option value='전체'>전체</option>
                       <option value='서울'>서울특별시</option>
                       <option value='부산'>부산광역시</option>
                       <option value='대구'>대구광역시</option>
                       <option value='인천'>인천광역시</option>
                       <option value='광주'>광주광역시</option>
                       <option value='대전'>대전광역시</option>
                       <option value='울산'>울산광역시</option>
                       <option value='경기'>경기도</option>
                       <option value='강원'>강원도</option>
                       <option value='충북'>충청북도</option>
                       <option value='충남'>충청남도</option>
                       <option value='전북'>전라북도</option>
                       <option value='전남'>전라남도</option>
                       <option value='경북'>경상북도</option>
                       <option value='경남'>경상남도</option>
                       <option value='제주'>제주도</option>
                    </select>                                                  
                                                  구/군: 
                    <select name='county'  class=select>
                       <option value=''>전체</option>
                    </select>
</form> 

</body>
</html>

 

3. 직접 만들어본 것(팀 선택 시, 해당 팀이 맡은 지역 선택)

<h5 class="modal_subtit">팀/지역 선택</h5>

<table class="table table-bordered no-padding text-sm">
    <colgroup>
        <?
        if($mobile_flag == 1)
        {
        echo "<col width='21%'>";
        echo "<col width='79%'>";
        } // if($mobile_flag == 1)
        else
        {
        echo "<col width='20%'>";
        echo "<col width='80%'>";
        } // else
        ?>
    </colgroup>
    <tbody>
        <tr class="device_control_type">
            <td class="text-left">공사지역</td>
            <td>
                <select onchange="categoryChange(this)" class="form-control" style="width:50%; float:left">
                    <option value=''>(1) 권역팀 선택</option>
                    <option value="a">전남팀</option>
                    <option value="b">전북팀</option>
                    <option value="c">광주팀</option>
                </select>

                <select name="cals09" id="cals09" class="form-control" style="width:50%; float:right">
                    <option value=''>(2) 세부 지역 선택</option>
                </select>

<script>
function categoryChange(e) {
    var good_a = ["서광주","상무","남광주","광주","화순","나주","함평","영광","목포","동목포","하당","무안","목포도서","해남","완도","진도","강진", "장흥", "영암", "그 외"];
    var good_b = ["북전주","동전주","남전주","전주","팔복","봉동","삼례","무주","진안","장수","군산","동군산","서군산","익산","부송","김제","함열","남원","임실","순창","정읍","고창","부안","신태인","완주", "그 외"];
    var good_c = ["동광주","본촌","광산","광하남","송정","장성","담양","곡성","순천","북순천","동순천","구례","고흥","보성","벌교","여수","여천","동여수","북여수","광양","서광양", "그 외"];
    var target = document.getElementById("cals09");

    if(e.value == "a") var d = good_a;
    else if(e.value == "b") var d = good_b;
    else if(e.value == "c") var d = good_c;

    target.options.length = 0;

    for (x in d) {
        var opt = document.createElement("option");
        opt.value = d[x];
        opt.innerHTML = d[x];
        target.appendChild(opt);
    }
}
</script>
            </td>
        </tr>
    </tbody>
</table>

 

 

4. 설정 후 or 새로고침해도 정보를 다시 가져올 수 있게 


if(isset($_REQUEST["cons_cons_region"]) && $_REQUEST["cons_cons_region"] != "") $requestParam_arr["cons_cons_region"] = xss_injection_filter($_REQUEST["cons_cons_region"]);
else $requestParam_arr["cons_cons_region"] = "";
if(isset($_REQUEST["cons_cons_region_factionation"]) && $_REQUEST["cons_cons_region_factionation"] != "") $requestParam_arr["cons_cons_region_factionation"] = xss_injection_filter($_REQUEST["cons_cons_region_factionation"]);
else $requestParam_arr["cons_cons_region_factionation"] = "";






<?
if(strlen($requestParam_arr["cons_cons_region_factionation"]) > 0)
{
	echo "<body class='skin-blue sidebar-mini' onLoad=\"statch_list();getInfo();categoryChange('".$requestParam_arr["cons_cons_region_factionation"]."')\">";
} // if(strlen($requestParam_arr["cons_cons_region_factionation"]) > 0)
else
{
	echo "<body class='skin-blue sidebar-mini' onLoad='statch_list();getInfo()'>";
} // else
?>









<td>
									<select onchange="categoryChange(this.value)" name="cons_cons_region_factionation" id="cons_cons_region_factionation" class="form-control" style="width:49%">
										<option value=''>(1) 권역팀 선택</option>
<?
$arr = array();
$arr["x"] = "전체";
$arr["a"] = "전남팀";
$arr["b"] = "전북팀";
$arr["c"] = "광주팀";
$arr["d"] = "그외";

foreach($arr as $key => $val)
{
	if($key == $requestParam_arr["cons_cons_region_factionation"])	$checked = "selected";
	else															$checked = "";

	echo "<option value='".$key."' ".$checked.">".$val."</option>";
} // foreach($arr as $key => $val)
?>
									</select>

									<select  name="cons_cons_region" id="cons_cons_region" class="form-control" style="width:49%">
										<option value=''>(2) 세부 지역 선택</option>
									</select>

									<script>
									function categoryChange(e) {
										var good_x = ["공사장 전체"];
										var good_a = ["전남권역 전체 공사장","서광주","상무","남광주","광주","화순","나주","함평","영광","목포","동목포","하당","무안","목포도서","해남","완도","진도","강진", "장흥", "영암"];
										var good_b = ["전북권역 전체 공사장","북전주","동전주","남전주","전주","팔복","봉동","삼례","무주","진안","장수","군산","동군산","서군산","익산","부송","김제","함열","남원","임실","순창","정읍","고창","부안","신태인","완주"];
										var good_c = ["광주권역 전체 공사장","북광주", "동광주","본촌","광산","광하남","송정","장성","담양","곡성","순천","북순천","동순천","구례","고흥","보성","벌교","여수","여천","동여수","북여수","광양","서광양"];
										var good_d = ["그 외"];
										var target = document.getElementById("cons_cons_region");



										if(e =="x") var d = good_x;
										else if(e == "a") var d = good_a;
										else if(e == "b") var d = good_b;
										else if(e == "c") var d = good_c;
										else if(e == "d") var d = good_d;

										target.options.length = 0;




										for (x in d) {
											console.log(x);
											var opt = document.createElement("option");
											opt.value = d[x];
											opt.innerHTML = d[x];
											console.log("<?=$requestParam_arr["cons_cons_region"]?>");
											if(d[x] == '<?=$requestParam_arr["cons_cons_region"]?>')
											{
												opt.setAttribute('selected', '');
											}
											target.appendChild(opt);
										}
									}
									</script>
								</td>
728x90
반응형