본문 바로가기

JavaScript

<select> 태그 안에서 선택된 <option> 값 가져오기 (options.selectedIndex)

 

<select id="sales_type">
    <option>전체</option>
    <option num="0">ups</option>
    <option num="1">type1</option>
    <option num="2">type2</option>
    <option num="3">type3</option>
    <option num="4">type4</option>
    <option num="5">type5</option>
    <option num="6">type6</option>
    <option num="7">type7</option>
    <option num="8">type8</option>
    <option num="9">type9</option>
</select>


위래처럼 select 태그가 있고
그 안에 option 태그들이 있다.

여기서 사용자가 어떤 option을 선택했는지 
값을 받아오려면 어떻게 해야 할까?

document.querySelector('#sales_type').options


위처럼 select태그.option 를 console로 출력했을 때 아래처럼 나온다.

HTMLOptionsCollection(11) [option, option, option, option, option, option, option, option, option, option, option, selectedIndex: 6]
0: option
1: option
2: option
3: option
4: option
5: option
6: option
7: option
8: option
9: option
10: option
length: 11
selectedIndex: 6
[[Prototype]]: HTMLOptionsCollection



아래쪽에 보면 selectedIndex 라는 값이 있다.
현재 select 안에서 선택돼 있는 option의 index 값이다.
이 값에 아래처럼 접근할 수 있다.

document.querySelector('#sales_type').options.selectedIndex
document.querySelector('#sales_type').options['selectedIndex']


여기서 내가 신경 쓰이는 점은 접근하는 방식이다.
select요소.options.selectedIndex 
이렇게 객체처럼 속성값으로 접근해도 되고
select요소.options['selectedIndex']
이렇게 배열처럼 불러와도 접근할 수 있다.

또한 배열처럼 접근했을 때,
option 태그에 해당하는 0부터 10까지를 index로 넣어주면
해당 option 요소 접근할 수 있다.
select요소.options[0]
select요소.options[7]
select요소.options[10]
그런데 console 에 출력된 값들을 보면
length 값은 select요소.options[11] 처럼 보이고
selectedIndex 값은 select요소.options[12] 처럼 보이는데,
이렇게 접근하면 undefined 가 출력된다.

select요소.options['selectedIndex']로 접근할 때는 리스트처럼 접근할 수 있는 것처럼 보인다.

그럼 리스트처럼 index로 접근할 수도 있을까?
그렇지 않다.

select요소.options[12] 처럼 index로 접근하는 것은 불가능하다.

select에서 선택된 option의 index 값을 알 수 있으므로
이제 option들이 모여 있는 list에서 해당 index를 넣어주면
선택된 option 요소에 접근할 수 있다.

let sel = document.querySelector('#sales_type');
let op = sel.options[sel.options.selectedIndex];

선택된 option 요소에 접근했으니, 그 값을 꺼내오기만 하면 된다.

let sel = document.querySelector('#sales_type');
let op = sel.options[sel.options.selectedIndex];
let val = op.value;
let val = op.innerHTML; //위와 같은 기능
let val = sel.options[sel.options.selectedIndex].value //위와 같은 기능
반응형