How to Get the Value of Selected Option in a Select Box
In this tutorial, you will learn how to get the value of the selected option in the select box using jQuery. There are two methods of getting the value of the selected option. You can either select text or find the position of it in a drop-down list by using the option:selected attribute or the val() method in jQuery.
The val() method returns the value of selected attribute value.
let selectedValue = $("#selectVal option:selected").val();
The text() method returns a string of the selected option.
let selectedValue = $("selectVal option:selected").text();
Let's show what will return these two methods with the following example:
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
</head>
<body>
<form>
<label>Select Names:</label>
<select class="selectVal">
<option value="1">Tom</option>
<option value="2">John</option>
<option value="3">James</option>
<option value="4">Ann</option>
<option value="5">Maria</option>
</select>
</form>
<script>
$(document).ready(function() {
$("select.selectVal").change(function() {
let selectedItem = $(this).children("option:selected").val();
alert("You have selected the name - " + selectedItem);
});
});
</script>
</body>
</html>
The val() method will select the value of the option for example "1", and if you want to get the string "Tom" you can use the text() method.
The text() and val() Methods
The text() method will set or return the text content of the selected elements.
It returns the text content of all matched elements. When it is used to set content, it overwrites the content of all matched elements.
The val() method is an inbuilt method in jQuery, which is used to get the values of form elements (e.g., input, select, textarea). It will return the value of the value attribute of the first matched element.