Friday, August 25, 2017

Dynamically populate a select element from JSON data with jQuery/Ajax

<html>
  <head>
    <script type="text/JavaScript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
  </head>
  <body>
    <select id="people"></select>
  </body>

The JSON file we’ll be using consists of a collection of ‘person’ data in a valid JSON form, such as:
{"person": [
  {
    "id": "1",
    "name": "Person1"
  },
  {
    "id": "2",
    "name": "Person2"
  },
  {
    "id": "3",
    "name": "Person3"
  }

]}

  <script type="text/JavaScript">

//getJSON
    //get a reference to the select element
    var $select = $('#people');
    //request the JSON data and parse into the select element
    $.getJSON('person.JSON', function(data){
      //clear the current content of the select
      $select.html('');
      //iterate over the data and append a select option
      $.each(data.person, function(key, val){
        $select.append('<option id="' + val.id + '">' + val.name + '</option>');
      })
    });

//AJAX
//get a reference to the select element
$select = $('#people');
//request the JSON data and parse into the select element
$.ajax({
  url: 'person.JSON',
  dataType:'JSON',
  success:function(data){
    //clear the current content of the select
    $select.html('');
    //iterate over the data and append a select option
    $.each(data.person, function(key, val){
      $select.append('<option id="' + val.id + '">' + val.name + '</option>');
    })
  },
  error:function(){
    //if there is an error append a 'none available' option
    $select.html('<option id="-1">none available</option>');
  }

});
  </script>
</html>
https://developerdan77.wordpress.com/2011/10/14/dynamically-populate-a-select-element-from-json-data-with-jquery/

No comments:

Post a Comment