Ad

Thursday 12 June 2014

How to load dropdown list dynamically using Jquery

In most scenarios we may need to load the drop down list dynamically with the values fetched from the database.Using jquery loading the dropdown list is very simple and easy to code.Lets assume we need to load the drop down with the city names fetched from the backend.The sample code for this is shown below:

<html>                                                                                                                                                    
<head>
<title>Dropdown sample</title>
<script type="text/javascript" src="jquery-2.1.1.min.js" ></script>
<script type="text/javascript">

function Load() {
   var cityobjArray = [
  {cityId:1,cityName:"Chennai"},
  {cityId:2,cityName:"Mumbai"},
  {cityId:3,cityName:"Banglare"},
  {cityId:4,cityName:"Pune"},
   ];
var cityDropdown = $('#cityDrpDown');

$.each(cityobjArray , function(index, cityobj) {
        cityDropdown.append(
         $('<option/>', {
                          value: cityobj.cityId,
                          text: cityobj.cityName
                        })
           );
        });
}

function unLoad() {
 $('#cityDrpDown').empty();
}
</script>
</head>
<body>
<table border="1">
<tr>
<td>
<B>To Load DropdownList dynamically</B><BR><BR>
Select City:<select  id="cityDrpDown"/></select>
<BR><BR>
<input type="button" value="Load" onclick="Load()"/>
<input type="button" value="Unload" onclick="unLoad()"/>
</td>
</tr>
</table>
</body>
</html>

  • Lets assume cityobjectArray is the Json data array we fetched from database which we need to load in the drop down list.
  • As shown in Load method,we iterate the cityobjectArray using $.each jquery method and for each cityobject we add the option object ("referenced using $(<option/>") to the dropdown list.The value and text of the Option object will set from Cityobject attributes cityid and cityname. 
  • To clear the dropdown list we use the jquery method empty() as shown in unLoad() method.

Demo:


To Load DropdownList dynamically

Select City:



No comments:

Post a Comment