Dynamically Adding Dropdown using JQuery


Audience: Beginners

This article is targeted to beginners in Jquery.

In this article, we will see

  1. Create Drop Down dynamically
  2. Adding options to Drop down dynamically.

image1.gif

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

    image2.gif

  2. Adding option by below script

    image3.gif

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

    image4.gif

Output

image5.gif

 

Up Next
    Ebook Download
    View all
    Learn
    View all