【问题标题】:How do i parse JSON file into html table depending on dropdown selection using javascript?如何根据使用 javascript 的下拉选择将 JSON 文件解析为 html 表?
【发布时间】:2017-09-26 22:16:38
【问题描述】:

我有一个 JSON 文件,其中包含一些对象。 希望根据下拉选择填充对象。 下拉列表包含所有“级别”值,我只需要显示包含等于用户选择的“级别”值的对象。 请看以下链接

https://fiddle.jshell.net/agbpr021/

for (var i = 0; i < allData.length; i++) {
    var x = document.getElementById("level").value;
    if(x = allData.level)
        tr = table.insertRow(-1);
        for (var j = 0; j < col.length; j++) {
            var tabCell = tr.insertCell(-1);
            tabCell.innerHTML = allData[i][col[j]];
        }
    }
            // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
    var divContainer = document.getElementById("showData");
    divContainer.innerHTML = "";
    divContainer.appendChild(table);

【问题讨论】:

  • 请在问题中包含您的代码,通常最好至少包含尝试自己回答问题的尝试,无论是对还是错。

标签: html json dropdown


【解决方案1】:

这应该会为您提供您正在寻找的结果。可能是一种更有效的方法,尤其是我如何为表格创建 html,但它应该会给你想要的输出。

function CreateTableFromJSON()
{
  // only included this so snippet would work
  allData = [
    { "Level": "a", "Country": "Unknown", "Currency": "USD" },
    { "Level": "a", "Country": "All", "Currency": "BRL" },
    { "Level": "b", "Country": "All", "Currency": "EUR" },
    { "Level": "c", "Country": "All", "Currency": "EUR" },
    { "Level": "d", "Country": "None", "Currency": "EUR" }
  ]
    
  var x = document.getElementById("Levels").value;
  var index = -1;
  for (var i = 0; i < allData.length; i++) {
      if (allData[i].Level == x)
          index= i;
  }

  var html = "";
  if (index != -1) {
      // probably a better way to do this portion
      html = "<table><thead><tr><th>Level</th><th>Country</th><th>Currency</th></tr></thead><tbody><tr>";
      html += "<td>" + allData[index].Level + "</td>";
      html += "<td>" + allData[index].Country + "</td>";
      html += "<td>" + allData[index].Currency + "</td>";
      html += "</tr></tbody></table>";
  } else {
      html = "Please make a selection";
  }

  // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
  var divContainer = document.getElementById("showData");
  divContainer.innerHTML = html;
}
<p>levels</p>
<select id="Levels">
  <option value="Null" id="m">Choose level</option>
  <option value="a" id="A">a</option>
  <option value="b" id="B">b</option>
  <option value="c" id="C">c</option>
  <option value="d" id="D">d</option>
</select>
<br /><br />
<!--Button-->
<input type="button" onclick="CreateTableFromJSON()" value="Go" />
<div id="showData"></div>
<br>	

编辑:我想提一下真正聪明的人已经组合了工具来处理这个问题。 React、Vue 和 Angular 是一些拥有此类工具的示例。

编辑:在 allData 中添加了错误索引检查

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多