카테고리 없음

[자바 스크립트] 선택한 옵션 ID를 얻는 방법은 무엇입니까?

필살기쓰세요 2021. 1. 9. 17:20

다음과 같이 간단합니다.

options[selectedIndex].id
-------------------

너무 많은 가정을하지 않고 (즉, select 는 유효한 SELECT 요소 임)

var options = select.options;
var id      = options[options.selectedIndex].id;
var value   = options[options.selectedIndex].value;

또는,

var options = select.options;
var value   = (options.selectedIndex != -1) ? options[selectedIndex].value : null;
var id      = (options.selectedIndex != -1) ? options[selectedIndex].id : null;

항상 허위 (또는 false로 평가되는 값)를 확인하십시오 . Ex 2는 변수를 null로 설정합니다 (선택된 항목이없는 경우).



출처
https://stackoverflow.com/questions/1904882