Get Selected Items From DropDown control using jQuery

Here’s a very simple way to get the selected items in a DropDownList. Just use the jQuery change() method and write the results to a div control

Single Selection

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Get Selected Item - DevCurry.com</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(function () {
$('#ddl').change(function () {
$('#divone').text($(this).find(":selected").text());
});

});
});
</script>
</head>
<body>
<select id="ddl">
<option value="Tomatoes">Tomatoes</option>
<option value="Potatoes">Potatoes</option>
<option value="Onion">Onion</option>
<option value="Olives">Olives</option>
</select>
<br />
<div id="divone" />
</body>
</html>


Multiple Selection



<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Get Selected Item - DevCurry.com</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(function () {
$('#ddl').change(function () {
var sel = "";
$(this).find(":selected").each(function () {
sel += $(this).text() + " ";
});
$("#divone").text(sel);
});
});
</script>
</head>
<body>
<select id="ddl" multiple="multiple">
<option value="Tomatoes">Tomatoes</option>
<option value="Potatoes">Potatoes</option>
<option value="Onion">Onion</option>
<option value="Olives">Olives</option>
</select>
<br />
<div id="divone" />
</body>
</html>



When the user selects an item from the DropDown by clicking and releasing the mouse button, the change event is fired. We retrieve the text for each selected (using each() and write it in a div.

image

See a Live Demo






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

prapoorna said...

I am very thankful to your code, thanq so much, ..prapoorna

Unknown said...

thanks. it's useful. :)