This content originally appeared on CodeSource.io and was authored by Deven
In this article, you are going to learn about how to get selected options value in jQuery.
jQuery is a speedy, lightweight, and easy-to-learn JavaScript library. With this library, you can manipulate the HTML DOM tree as well as event handling and bring interactivity to your web page. jQuery provides lots of library methods, :selected selector in combination with the val() method is one of them to get the value of the selected option.
Let’s see an example to make things clear. Suppose you have different age limits in multiple select boxes and you want to show a particular value when a specific option is selected. You can simply do it with jQuery. Follow the example code below:
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Get Selected Option Value</title>
</head>
<body>
<form>
<label>Select Your Age:</label>
<select class="age">
<option value="Child">6 - 17</option>
<option value="Adult">18 - 49</option>
<option value="Old">50 - 70+</option>
</select>
</form>
</body>
</html>
Here in the HTML file we write different age limits and give value for each one but if we try to get our desired output it will not work because we didn’t implement functionality for it.
jQuery Code :
<script src="<https://code.jquery.com/jquery-3.5.1.min.js>"></script>
<script>
$(document).ready(function(){
$("select.age").change(function(){
var selectedCountry = $(this).children("option:selected").val();
alert("You are - " + selectedCountry);
});
});
</script>
We have to write this jQuery code to make things work. We link jQuery in <script> tag and write this code. You can download the jQuery file and make a separate file. But we did it in the HTML file after the <title> tag to keep things simple.
Output:
Here, we can see different age limits. From these, we select age limit in between 18-49 and let’s see what value we’ve got.
We can see that we got an alert with a message of “You are – Adult”. If you select the age limit between 6-17 you will get a different value. This is how you can get selected option value in jQuery.
The post How to get selected option value in jQuery appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Deven
Deven | Sciencx (2021-11-01T15:49:48+00:00) How to get selected option value in jQuery. Retrieved from https://www.scien.cx/2021/11/01/how-to-get-selected-option-value-in-jquery/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.