기계는 거짓말하지 않는다

select option 선택, 값 control 본문

Web/JS

select option 선택, 값 control

KillinTime 2020. 12. 3. 00:08

JavaScript

var selectBox = document.getElementById("selectID");	// id로 object 얻기
alert(selectBox.options.length);	// option 개수
alert(selectBox.selectedIndex);	// 선택된 option index
alert(selectBox.options[selectBox.selectedIndex].id);	// 선택된 option id
alert(selectBox.options[selectBox.selectedIndex].value);	// 선택된 option value
alert(selectBox.options[selectBox.selectedIndex].text);	// 선택된 option text
selectBox.selectedIndex = 2;	// option 선택 index 강제 변경

값 얻기 뿐만 아니라 값 변경도 가능하다. ex) selectBox.options[selectBox.selectedIndex].text = "changeText";

 

JQuery

alert($("#selectID option").length);	// option 개수
alert($("#selectID option:selected").index());	// 선택된 option index
alert($("#selectID option:selected").attr("id"));	// 선택된 option id
alert($("#selectID option:selected").val());	// 선택된 option value
alert($("#selectID option:selected").text());	// 선택된 option text
$("#selectID option:eq(4)").prop("selected", true);	// option 선택 index 강제 변경

 

Test

<body>
	<select id="mySelect">
    		<option id="op" value="select" selected>옵션을 선택하세요</option>
		<option id="op1" value="val1">옵션 1</option>
		<option id="op2" value="val2">옵션 2</option>
		<option id="op3" value="val3">옵션 3</option>
		<option id="op4"value="val4">옵션 4</option>
	</select>
	<a onclick="check()"><b style="font-size:20px; cursor:pointer; text-decoration:underline;">확인</b></a>
	
	<script>
		function check() {
			var selectBox = document.getElementById("mySelect");
			
			console.log("Java Script");
			console.log("option size: " + selectBox.options.length);
			console.log("selected index: " + selectBox.selectedIndex);
			console.log("selected option id: " + selectBox.options[selectBox.selectedIndex].id);
			console.log("selected option value: " + selectBox.options[selectBox.selectedIndex].value);
			console.log("selected option text: " + selectBox.options[selectBox.selectedIndex].text);
			selectBox.selectedIndex = 2;
			console.log("change index: " + selectBox.selectedIndex);
			
			console.log("JQuery");
			console.log("option size: " + $("#mySelect option").length);
			console.log("selected index: " + $("#mySelect option:selected").index());
			console.log("selected option id: " + $("#mySelect option:selected").attr("id"));
			console.log("selected option value: " + $("#mySelect option:selected").val());
			console.log("selected option text: " + $("#mySelect option:selected").text());
			$("#mySelect option:eq(4)").prop("selected", true);
			// $("#mySelect option").eq(4).prop("selected", true); 동일
			console.log("change index: " + $("#mySelect option:selected").index());
		}
	</script>
</body>

HTML
Console

'Web > JS' 카테고리의 다른 글

radio 버튼 선택, 값 control  (0) 2020.12.03
checkbox 확인, 변경, 강제클릭  (0) 2020.12.02
오브젝트 얻어오기 (getElement)  (0) 2020.12.01
Comments