반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

그럴 수도 있지

[Javascript] select option control (value값으로 selected 하기) 본문

Javascript

[Javascript] select option control (value값으로 selected 하기)

디벅 2021. 7. 19. 09:20
반응형

select 박스에 있는 option값을 선택해줘야 할 때가 있다. 예를 들어, 작성 된 내용을 바탕으로 수정 시라던가, 버튼을 누르면 자동으로 선택해줘야한다던가.

 

value값을 알면 selected 가능한 간단한 예제다. 

 

< HTML 소스 >

<!DOCTYPE html>
<head>
  <script src="example.js"  type="text/javascript"></script>
</head>
<select id='fruit'>
  <option value='apple'>사과</option>
  <option value='strawberry'>딸기</option>
  <option value='grape'>포도</option>  
</select>
<input type='text' id='searchValue'>
<input type='button' onclick='selectedControl()' value='선택'>
</html>

대충 이렇게 3개의 옵션이 있는 select 박스가 만들어지고, value값을 입력 받을 input, 그리고 javascript 함수를 실행시켜줄 선택 박스를 만들었다.

 

< 자바스크립트 소스 >

function selectedControl(){
  const el = document.getElementById('fruit');  //select box
  const len = el.options.length; //select box의 option 갯수
  const str = document.getElementById('searchValue').value; //입력 받은 value 값
  //select box의 option 갯수만큼 for문 돌림
  for (let i=0; i<len; i++){  
  	//select box의 option value가 입력 받은 value의 값과 일치할 경우 selected
    if(el.options[i].value == str){
    	el.options[i].selected = true;
    }
  }  
}

 

grape를 입력받아 선택하면 짜란-. 

너무 간단해서 민망, 머쓱,^ㅛ^;;;

 

 

* 예시 파일 

example.js
0.00MB
select_ex.html
0.00MB

 

반응형