본문 바로가기
javascript/javascript

javascript select 선택된 옵션 값 가져오기

by 알찬 퍼블리셔 2022. 8. 29.
728x90
반응형
//선택자를 통해 원하는 select 를 가져온다
let select = document.getElementById('select');

//select.selectedIndex --> selected된 옵션 번호 
select = select.options[select.selectedIndex].value;

 

select.selectedIndex 값 이용

 

 

 

https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedIndex

 

HTMLSelectElement.selectedIndex - Web APIs | MDN

The HTMLSelectElement.selectedIndex is a long that reflects the index of the first or last selected <option> element, depending on the value of multiple. The value -1 indicates that no element is selected.

developer.mozilla.org

또는 

 

//선택자를 통해 원하는 select 를 가져온다
let select = document.getElementById('select');

//select.selectedOptions --> selected된 옵션 리스트 
//select 가 multiple 일 경우 선택된 여러개의 옵션 값을 가져올 수 있음
// value 또는 label 을 통해 가져올 수 있다

let selectedVal = select.selectedOptions[0].value;
let selectedTxt = select.selectedOptions[0].label;

selectedOptions = select.selectedOptions;

for(let i=0; i<selectedOptions.length; i++){
	console.log(selectedOptions[i].value);
	console.log(selectedOptions[i].label);
}

 

select.selectedOptions 값 이용

 

 

 

 

https://developer.mozilla.org/ko/docs/Web/API/HTMLSelectElement/selectedOptions

 

HTMLSelectElement.selectedOptions - Web API | MDN

The read-only HTMLSelectElement property selectedOptions contains a list of the <option> elements contained within the <select> element that are currently selected. The list of selected options is an HTMLCollection object with one entry per currently selec

developer.mozilla.org

 

728x90
반응형

댓글