Dynamically Adding Drop down using JQuery

Audience: Beginners

This article is targeted to beginners in Jquery.

In this article, we will see

1. Creating Drop Down dynamically

2. Adding options to Drop down dynamically.

clip_image001

So, on $(document).ready(function() {}; , we will create drop down and add options to that at runtime. We are going to add two drop downs

MyPage.htm

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {

alert("Hello World!!!");

var data = {     'Country': 'India',     'Country1': 'USA', 'Country2': 'Australia',     'Country3': 'Srilanka'}  ;

var s = $('<select />');

for(var val in data)
{
 $('<option />', {value: val, text: data[val]}).appendTo(s);
}

s.appendTo('body');

var data1 = {     'City': 'New Delhi',     'City2': 'WDC' ,'City3': 'Adilade','City4': 'Colombo'}  ;

var s1 = $('<select />');

for(var val in data1)
{
 $('<option />', {value: val, text: data1[val]}).appendTo(s1);
}

s1.appendTo('body');

});
</script>
</script>
</head>
<body>
</body>
</html>


Explanation

1. Creating dropdown by

clip_image002

2. Adding option by below script

clip_image004

3. Adding dropdown to body of HTML. You can add anywhere you want like div or form

clip_image005

Output

clip_image001[1]

Published by

Dhananjay Kumar

Dhananjay Kumar is Developer Evangelist for Infragistics. He is a 8 times Microsoft MVP and well respected Developer Advocate in India.He is the author of 900+ Blog Posts, and can often be found speaking around India at conferences and hosting free workshops for programmers across the country. So far, he has hosted 60 free workshops on various topics like JavaScript, Angular, WCF, ASP.NET MVC, C#, Azure etc. Follow him on twitter @debug_mode for all the updates about his blog posts and workshops. You can send him email at debugmode [at] outlook [dot] com

2 thoughts on “Dynamically Adding Drop down using JQuery”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s