In this post, we will learn how to get the value of selected option in select box using jQuery. For this we use jQuery :selected selector with the combination of val() method.


How To Get the Value of Selected Option in Select Box Using jQuery ?


jQuery :selected Selector

In this example below we use jQuery :selected selector for get the value of selected option. 

<!DOCTYPE html>
<html>
<head>
<title>How To Get the Value of Selected Option in Select Box Using jQuery ?</title>
</head>
<body>

<form>
<label>Select Number:</label>
<select class="number">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</form>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("select.number").change(function(){
var selectedNumber = $(this).children("option:selected").val();
console.log(selectedNumber);
});
});
</script>

</body>
</html> code-box

If you want to get the text of selected option. For this we use text() instead of val() method.

<!DOCTYPE html>
<html>
<head>
<title>How To Get the Value of Selected Option in Select Box Using jQuery ?</title>
</head>
<body>

<form>
<label>Select Number:</label>
<select class="number">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</form>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("select.number").change(function(){
var selectedNumber = $(this).children("option:selected").text();
console.log(selectedNumber);
});
});
</script>

</body>
</html> code-box

Summary

In this post we learn how to get the value of selected option in select box using jQuery. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts.

Post a Comment

Previous Post Next Post