상세 컨텐츠

본문 제목

[Javascript/JQuery] 선택한 SelectBox의 index 값 알아내기

개발/개발 기타

by 똘똘이박사 2018. 7. 26. 22:11

본문

SelectBox에서 어떤 값을 선택했을때

선택한 값이나 내용을 알아 내는 방법은 간단하다.


그런데 해당 옵션들의 index 값을 알아 내는 방법은  생각보다 간단하지 않아서

알아낸 방법 2가지를 정리해 본다.




방법1. Javascript를 이용한 방법


var x = document.getElementById("SelectBoxId").selectedIndex;

var y = document.getElementById("SelectBoxid").options;

var idx = y[x].index;

console.log("선택한 index : " + idx);




방법2. JQuery 를 이용한 방법


var idx = $("#SelectBoxId option").index( $("#SelectBoxId option:selected") );

console.log("선택한 index : " + idx);





2018년 front-end 기술 스택에서 jQuery가 필수가 아닌 옵션으로 빠졌다.

2번 방법을 알고 있으면 좋겠지만, 

앞으로는 기본이 되는 Javascript에 충실한 1번 방법도 알아 두는게 좋을 듯 하다.

반응형

관련글 더보기