본문 바로가기

JavaScript/jQuery

[jQuery] select 태그에서 jquery 활용하기

 

jquery를 사용해 <select> 태그에서 선택된 요소 찾기

 

 

일단 간단히 html 을 작성한다. html 안에 스크립트 코드도 작성했다.

<html>
<head>
	<title>test</title>
</head>
<body>
	<span>당신이 좋아하는 과일은?&nbsp;</span>
	<select class='fruitSet'>
		<option class='fruit' id='apple' value="apple">사과</option>
		<option class='fruit' id='orange' value="orange">오렌지</option>
		<option class='fruit' id='grape' value="grape" selected>포도</option>
		<option class='fruit' id='strawberry' value="strawberry">딸기</option>
		<option class='fruit' id='watermelon' value="watermelon">수박</option>
	</select>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
	<script>
		var getInitSelectedFruit = function() {
			var $fruitSet = $('.fruitSet');
			var idx = $fruitSet[0].selectedIndex;	//2
			var fruitSelected = $fruitSet[0].children[idx];
			var fruitName = fruitSelected.value;	//grape

			console.log('선택된 과일인덱스 = ' + idx + ' | 과일 = ' + fruitName);
		}
	
		jQuery(document).ready(function(){
			getInitSelectedFruit();
		});
	</script>
</body>
</html>

 

 

 

콘솔 결과

선택된 과일인덱스 = 2 | 과일 = grape

'JavaScript > jQuery' 카테고리의 다른 글

[jQuery] 라이브러리 설정 및 test (CDN 및 다운로드)  (0) 2022.04.15