How to create Select Element from JSON data using Jquery

How to create Select Element from JSON data using Jquery

By Yashwant Chavan, Views 21927, Date 10-Oct-2015

In this Jquery tutorial we will learn about how to create Select Element from JSON data using Jquery.

tags jquery

Define JSON data

Define the JSON data object from which you need to create the select element, data is in the form of key value pair. "value" represent option value and "text" represent text of option element.

var json = [       
     { "value": "pune", "text": "Pune"  },
     { "value": "mumbai", "text": "Mumbai"  },
     { "value": "nashik", "text": "Nashik"  }
   ];

Create and loop Select options

First we need to create select DOM element using Jquery. Once the select object is created we are going to append the option elements. Here we have iterated JSON data using $.each(json,function(index,json){ ... } loop.

 var select = $("<select></select>").attr("id", "cities").attr("name", "cities");
 $.each(json,function(index,json){
  select.append($("<option></option>").attr("value", json.value).text(json.text));
 });     

Complete Example

In below example , click on "Create Select" button which will execute the logic to create option list.

<!DOCTYPE html>
<html>
   <head>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
      <script>
         $(document).ready(function(){  
          
          var json = [       
            { "value": "pune", "text": "Pune"  },
            { "value": "mumbai", "text": "Mumbai"  },
            { "value": "nashik", "text": "Nashik"  }
          ];
          
          $('#btn').click(function(){    
           var select = $("<select></select>").attr("id", "cities").attr("name", "cities");
           $.each(json,function(index,json){
            select.append($("<option></option>").attr("value", json.value).text(json.text));
           });     
           $("#container").html(select);
          });   
         });  
      </script>     
   </head>
   <style> 
      body{
      background-color:#6559EE;   
      margin:10px;
      font-weight:bold;
      font-size: 16px;
      }
      select {  
      color: #777;
      width:150px;  
      }
   </style>
   <body>
      <h1>Create Select from JSON data using Jquery</h1>
      <div id="container"></div>
      <p><input type="button" id="btn" value="Create Select"></p>
   </body>
</html>

Output

Create Select Element from JSON data using Jquery
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]