November 5, 2010

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



Giving me +1 tells me you liked this article! Thanks in advance


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

2 Responses to "Get Selected Items From DropDown control using jQuery"
  1. prapoorna said...
    January 5, 2012 at 1:53 AM

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

  2. huynh trang said...
    January 1, 2013 at 11:08 PM

    thanks. it's useful. :)

 

Copyright © 2009-2013 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions