基于select字段从json文件生成表

时间:2016-08-05 10:15:41

标签: javascript jquery json

是否可以根据选定的值从json文件自动创建表。

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

1 个答案:

答案 0 :(得分:0)

用你给出的json i' hv就是一个例子。看看这个。

$("#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);
  }
});

&#13;
&#13;
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);
    }
  });
});
&#13;
<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>
&#13;
&#13;
&#13;