Anusha Gonugunta Anusha Gonugunta - 3 months ago 9
JSON Question

Based on select field generate a table from json file

Is it possible to auto create a table from json files based on selected values.

$(document).ready(function(){
$("#dropdown_change").change(function(){
alert("Selected value is : " + document.getElementById("dropdown_change").value);
});

Answer

With your given json i'hv made an example. Look into this.

$("#dropdown_change").change(function() {
  var val = $(this).val();
  alert("Selected value is : " + val);
  var projects = PROJECTDETAILS.filter(function(pd) {
    return pd['Project key'] == val;
  })
  if (projects.length) {
    var html = '';
    projects.map(function(pro) {
      html += '<tr>';
      for (var i in pro) {
        html += '<td>' + pro[i] + '</td>';
      }
      html += '</tr>';
    })
    $('table').find('tr').not(':eq(0)').remove();
    $('table').show().append(html);
  }
});

var PROJECTDETAILS = [{
  "Project key": "Bluesky",
  "Employee Name": "anusha",
  "Issue Id": "0011",
  "Charge No": "1111",
  "Hours": "10"
}, {
  "Project key": "Bluesky",
  "Employee Name": "anusha",
  "Issue Id": "00123",
  "Charge No": "1111",
  "Hours": "10"
}, {
  "Project key": "project2",
  "Employee Name": "kavya",
  "Issue Id": "00452",
  "Charge No": "1111",
  "Hours": "10"
}]

$(document).ready(function() {
  $("#dropdown_change").change(function() {
    var val = $(this).val();
    alert("Selected value is : " + val);
    var projects = PROJECTDETAILS.filter(function(pd) {
      return pd['Project key'] == val;
    })
    if(projects.length){
      var html = '';
      projects.map(function(pro){
        html+='<tr>';
        for(var i in pro){
          html+='<td>'+pro[i]+'</td>';
        }
        html+='</tr>';
      })
      $('table').find('tr').not(':eq(0)').remove();
      $('table').show().append(html);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown_change">
  <option value="Bluesky">Bluesky</option>
  <option value="project2">project2</option>
</select>

<table style="display: none">
  <tr><th>Project key</th><th>Employee Name</th><th>Issue Id</th><th>Charge No</th><th>Hours</th></tr>
  </table>

Comments