List Items of a DropDownList using jQuery

Here’s a script that lists items of a DropDown/Select Box using jQuery. I have used the map(callback) function for this requirement

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>List Items of a DropDownList</title>
<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</
script>

<
script type="text/javascript">
$(function() {
$("#btnList").click(function() {
var ddlItems = $("#DDL option").map(function(a, b) {
return b.text; // to print value say -- b.value
}).get().join("<br/>");
$('#para').html(ddlItems);
});
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
select id="DDL">
<
option value="21">David</option>
<
option value="22">Jack</option>
<
option value="23">Jenny</option>
<
option value="24">Julia</option>
</
select>
<
br />
<
input id="btnList" type="button" value="Click Here to List Items" />
<
br />
<
p id="para" />
</
div>
</
form>
</
body>
</
html>



You can read more about Traversing/Map() . The get() function accesses all matched elements and passes it to map() as an array.

See a Live Demo

OUTPUT

image



Will you give this article a +1 ? Thanks in advance


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.

No comments: