javascript : 동적 select tag 구현

김선미·2022년 12월 12일
  • 사용자가 국가를 선택하면 국가에 따라 도시 옵션이 변경되는 select tag 연결을 구현하였다.
  • 처음엔 검색을 통해 jquery를 사용한 코드를 사용했지만 제대로 작동이 되지않고 jquery 문법을 모르는 채로 수정하기가 어려워서 js 코드로 변경하였다.

html 구현

  • 메인 검색 화면 html: 국가-도시 select
<select name="country" id="country" onchange="selectCountry(this, this.value)">
    <option value="국가">국가</option>
    <option value="한국">한국</option>
    <option value="일본">일본</option>
    <option value="중국">중국</option>
</select>
<select name="city" id="city">
    <option>도시</option>
</select>
  • 수정 modal html: 국가-도시 select
<input type="text" placeholder="국가" />
<select name="thirdCountry" id="thirdCountry" onchange="selectCountry(this, this.value)">
    <option value="국가">국가</option>
    <option value="한국">한국</option>
    <option value="일본">일본</option>
    <option value="중국">중국</option>
</select>
<br>
<input type="text" placeholder="도시" />
<select name="thirdCity" id="thirdCity">
    <option>도시</option>
</select>
  • 사용자 추가(행 추가) 메소드 html: 국가-도시 select
function addrow(){
    	var table = document.getElementById('list');
        var row = table.insertRow();

        var checkBox = row.insertCell(0);
        var id = row.insertCell(1);
        var name = row.insertCell(2);
        var gender = row.insertCell(3);
        var country = row.insertCell(4);
        var city = row.insertCell(5);

        checkBox.innerHTML = "<input type='checkbox' name='checkbox'>";

        id.innerHTML= "<input type='text' id='id2' name='id'  placeholder='아이디'/>";

        name.innerHTML = "<input type='text' id='name2' name='name' placeholder='이름'/></td>";

        gender.innerHTML = "<input type='radio' id='남자' name='gender2' value='M'>"
           +  "<label for='남자'></label>"
           +  "<input type='radio' id='여자' name='gender2' value='F'>"
           +  "<label for='여자'></label>";
           
       country.innerHTML = "<select name='secondCountry' id='secondCountry' onchange='selectCountry(this, this.value)'>"
       	+ "<option value='국가'>국가</option>"
       	+ "<option value='한국'>한국</option>"
       	+ "<option value='일본'>일본</option>"
       	+ "<option value='중국'>중국</option>"
       	+ "</select>";
       
       city.innerHTML = "<select name='secondCity' id='secondCity'>"
       + "<option>도시</option>"
       + "</select>"
    }

javascript 구현

  • 사용자가 국가를 선택했을 때 메소드를 통해 도시 옵션이 변경되게 한다.
 function selectCountry(param, value){
    	
      	let cityid;
    	let city;
    	cityid = param.id;
    	
    	if (cityid == 'country'){
    		city = document.querySelector('#city');
    	} else if (cityid == 'secondCountry'){
    		city = document.querySelector('#secondCity');
    	} else if (cityid == 'thirdCountry'){
    		city = document.querySelector('#thirdCity');
    	}
        
        countryOption = value;
        
        console.log("cityid=" + cityid + ", countryOption=" + countryOption + ", city=" + city);
    
       	let cities = {
        		korea: ['서울', '부산', '인천', '제주'],
        		japan: ['도쿄', '오사카', '삿포로', '오키나와'],
        		china: ['베이징', '상하이', "텐진", "하얼빈"]
        }
        
        let cityOption;
        
        switch (countryOption) {
        case '한국':
        	cityOption = cities.korea;
        	break;
        case '일본':
        	cityOption = cities.japan;
        	break;
        case '중국':
        	cityOption = cities.china;
        	break;
        
        }
        
        console.log(city);
        city.options.length = 0;
        for (let i=0; i<cityOption.length; i++){
        	let option = document.createElement('option');
			option.innerText = cityOption[i];
			console.log("append city=" + city);
        	city.append(option);
        	
        	
        }
        
        console.log("city=" + city);
        
    }
  • 사용자가 테이블의 행을 클릭 또는 더블클릭 했을 때 해당되는 사용자의 국가와 도시 옵션을 자동으로 불러오기 위해 changeCity 메소드를 구현하고 클릭, 더블클릭 메소드에서 사용하였다.
function rowClicked() {
    
    var table =document.getElementById('list');
    var rowList = table.rows;

    for (i=1; i<rowList.length; i++) {//thead부분 제외.

        var row = rowList[i];
        
        row.onclick = function(){
            toggleBtn();
            return function(){
                console.log("click");
                //개별적으로 값 가져오기
                var stringid =this.cells[1].innerHTML;
                var name = this.cells[2].innerHTML;
                var gender = this.cells[3].innerHTML;
                var country = this.cells[4].innerHTML;
                var city = this.cells[5].innerHTML;

                console.log(stringid,name,gender,country,city);

                document.getElementById('personalId').value = stringid;
                document.getElementById('personalName').value = name;
                $('input:radio[name=gender]:input[value=' + gender + ']').attr("checked", true);
                document.getElementById('country').value = country;
                /* document.getElementById('city').value = city; */
                //주석처리된 코드로 동작하지 않아서 changeCity 메소드를 구현하였다.
                
                var tagnum = "country";
                changeCity(tagnum, country, city);
                
            };//return
        }(row);
    }//for
}//function

var openid;
var openname;
var opengender;
var opencountry;
var opencity;

function rowDoubleClicked(){
    var table =document.getElementById('list');
    var rowList = table.rows;

    for (i=1; i<rowList.length; i++) {//thead부분 제외.

        var row = rowList[i];
        row.ondblclick = function(){
            console.log("dbclick");
            
            return function(){
                
                //개별적으로 값 가져오기
                
                console.log("this=" );
                console.log(this);
                console.log("this end");
                
                openid =this.cells[1].innerHTML;
                openname = this.cells[2].innerHTML;
                opengender = this.cells[3].innerHTML;
                opencountry = this.cells[4].innerHTML;
                opencity = this.cells[5].innerHTML;

                console.log("doubleclick =" + openid,openname,opengender,opencountry,opencity);

                document.getElementById('id').value = openid;
                document.getElementById('name').value = openname;
                $('input:radio[name=gender3]:input[value=' + opengender + ']').attr("checked", true);
                document.getElementById('thirdCountry').value = opencountry;
                /* document.getElementById('thirdCity').value = opencity; */
                //주석처리된 코드로 동작하지 않아서 changeCity 메소드를 구현하였다.
                
                var tagnum = "thirdCountry";
                changeCity(tagnum, opencountry, opencity);
                
                showModal();
            };
        }(row);
    }//for
}

function changeCity(tagnum, country,city){

    	let citytag;
    	if (tagnum == 'country'){
    		citytag = document.querySelector('#city');
    	} else if (tagnum == 'thirdCountry'){
    		citytag = document.querySelector('#thirdCity');
    	}
    	
    	
        let cities = {
        		korea: ['서울', '부산', '인천', '제주'],
        		japan: ['도쿄', '오사카', '삿포로', '오키나와'],
        		china: ['베이징', '상하이', "텐진", "하얼빈"]
        }
        
        let cityOption;
        
        switch (country) {
        case '한국':
        	cityOption = cities.korea;
        	break;
        case '일본':
        	cityOption = cities.japan;
        	break;
        case '중국':
        	cityOption = cities.china;
        	break;
        }
        
        citytag.options.length = 0;
        for (let i=0; i<cityOption.length; i++){
        	let option = document.createElement('option');
			option.innerText = cityOption[i];
			console.log("append change city=" + city);
        	citytag.append(option);
        	
        }
    	if (tagnum == 'country'){
    		document.getElementById('city').value = city;
    	} else if (tagnum == 'thirdCountry'){
    		document.getElementById('thirdCity').value = city;
    	}
        
    }
  • open~ 변수를 메소드 밖에서 선언하여 새 창이나 모달을 띄워도 변수의 값을 사용할 수 있게 구현하였다.
  • select tag 기능은 완성했지만, row click, row double click 메소드 실행시 최초에는 return function이 실행되지 않고, 두번째부터 실행된다. 그래서 return function을 제거했더니 원하는 this.cells[i] 값이 제대로 들어오지 않았다. 이번주 내로 해결하려고 한다.
profile
백엔드 개발 공부

0개의 댓글