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]

About these ads

One thought on “Dynamically Adding Drop down using JQuery

  1. Pingback: Monthly Report February 2011: Total Posts 14 « debug mode……

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s