How to fill json data to select element using jquery

Here we explain how to fill json data to select element/html combo box using jquery.

Suppose the json output is like
[
     {
          "Value":"1",
          "Text":"C"
     },
     {
          "Value":"2",
          "Text":"C++"
     },
     {
          "Value":"3",
          "Text":"PHP"
     },
     {
          "Value":"4",
          "Text":"JAVA"
     },
     {
          "Value":"5",
          "Text":"JAVASCRIPT"
     },
     {
          "Value":"6",
          "Text":"JSP"
     }
]


Then fill the above json data to the select element.

HTML code:
<select name="Languages"></select>

Javascript code:
var LanguagesJSON = [
     {
          "Value":"1",
          "Text":"C"
     },
     {
          "Value":"2",
          "Text":"C++"
     },
     {
          "Value":"3",
          "Text":"PHP"
     },
     {
          "Value":"4",
          "Text":"JAVA"
     },
     {
          "Value":"5",
          "Text":"JAVASCRIPT"
     },
     {
          "Value":"6",
          "Text":"JSP"
     }
]
var Languages = jQuery.parseJSON(LanguagesJSON);
for(var i=0;i<Languages.length;i++)
{
    var Option = "<option "+(i === 1 ? "selected" : "" )+ " value='"+Languages[i].Value+"'> "+Languages[i].Text+" </option>";
    $("select[name='Languages']").append(Option);
}


Output is:
<select name="Languages">
<option value="1">C</option>
<option value="2">C++</option>
<option value="3">PHP</option>
<option value="4">JAVA</option>
<option value="5">JAVASCRIPT</option>
<option value="6">JSP</option>
</select>

No comments:

Post a Comment