javascript - 尝试制作 HTML 表格并使用相同的 JSON 数据填充选择标签

标签 javascript jquery html json

我有一个 JSON 数据,我试图从中制作一个 HTML 表格和一个下拉列表,但面临呈现表格和下拉列表的问题。

我的 JSON:

[
  {
    "Category name": "juce",
    "Category Data": [
      {
        "Item Code": "1234",
        "Item Name": "juce1",
        "Quantity": "0"
      }
    ]
  },
  {
    "Category name": "juce",
    "Category Data": [
      {
        "Item Code": "1234",
        "Item Name": "juce2",
        "Quantity": "0"
      }
    ]
  },
  {
    "Category name": "rice",
    "Category Data": [
      {
        "Item Code": "1234",
        "Item Name": "rice1",
        "Quantity": "0"
      }
    ]
  },
  {
    "Category name": "rice",
    "Category Data": [
      {
        "Item Code": "1234",
        "Item Name": "juce2",
        "Quantity": "0"
      }
    ]
  },
  {
    "Category name": "roti",
    "Category Data": [
      {
        "Item Code": "1234",
        "Item Name": "roti1",
        "Quantity": "0"
      }
    ]
  },
  {
    "Category name": "roti",
    "Category Data": [
      {
        "Item Code": "1234",
        "Item Name": "juce2",
        "Quantity": "0"
      }
    ]
  }
]

我正在尝试制作一个 HTML 表格,其外部有下拉菜单,命名为类别名称。

就像在我的 JSON 中一样,我在下拉列表中有我想要的类别名称,以及在我的 HTML 表格中的其他数据。

当用户单击下拉列表中的任何类别时,HTML 表格将仅根据该类别名称进行填充。

'数量'这个字段是可编辑的,将由用户输入

我正在尝试的片段:

function addTable(tableData) {
  var col = Object.keys(tableData[0]);
  var countNum = col.filter(i => !isNaN(i)).length;
  var num = col.splice(0, countNum);
  col = col.concat(num);
  var table = document.createElement("table");
  var tr = table.insertRow(-1); // TABLE ROW.
  var colNum = col.length; //to improve the speed
  for (var i = 0; i < colNum + 1; i++) {
    var th = document.createElement("th"); // TABLE HEADER.
    if (i >= colNum) {
      th.innerHTML = "Quantity";
      tr.appendChild(th);
      tr.classList.add("text-center");
      tr.classList.add("head")
    } else {
      th.innerHTML = col[i];
      tr.appendChild(th);
      tr.classList.add("text-center");
      tr.classList.add("head")
    }
  }
  for (var i = 0; i < tableData.length; i++) {
    tr = table.insertRow(-1);
    for (var j = 0; j < col.length + 1; j++) {
      let tabCell = tr.insertCell(-1);
      var hiddenField = document.createElement("input");
      hiddenField.style.display = "none";
      var tabledata = tableData[i][col[j]];
      if (i > -1 && j >= colNum) {
        var quantityField = document.createElement("input");
        quantityField.style.border = "none";
        quantityField.style["text-align"] = "center";
        quantityField.setAttribute('name', 'Quantity');
        quantityField.setAttribute('autocomplete', 'on');
        quantityField.setAttribute('value', '0');
        quantityField.setAttribute('type', 'number');
        quantityField.setAttribute('required', 'required');
        quantityField.classList.add("dataReset");
        tabCell.appendChild(quantityField);
      } else {
        if (tableData[i]['Item Code'] === tableData[i][col[j]]) {
          tabCell.innerHTML = tabledata;
          hiddenField.setAttribute('name', 'Item_Code');
          hiddenField.setAttribute('value', tabledata);
          tabCell.appendChild(hiddenField);
        }
        if (tableData[i]['Item Name'] === tableData[i][col[j]]) {
          tabCell.innerHTML = tabledata;
          hiddenField.setAttribute('name', 'Item_Name');
          hiddenField.setAttribute('value', tabledata);
          tabCell.appendChild(hiddenField);
        }
        if (j > 1)
          tabCell.classList.add("text-right");
      }
    }
  }
  var divContainer = document.getElementById("HourlysalesSummary");
  divContainer.innerHTML = "";
  divContainer.appendChild(table);
  table.classList.add("table");
  table.classList.add("table-striped");
  table.classList.add("table-bordered");
  table.classList.add("table-hover");
}
addTable(tableData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="www.google.com" id="form1">
  <div class="row position-relative">
    <div class="col-lg-4">
      <h5 id="commonHeader">Category</h5>
      <select class="test" id="CategoryName" name="categoryCode">
        <option>All</option> <!-- this also i want to populate with the JSON DATA not statically,except All -->
        <option>juce</option>
        <option>rice</option>
        <option>roti</option>
      </select>
    </div>
  </div>
  <hr style="border: 1px solid black">
  <div class="table-responsive">
    <table class="w-100" id=HourlysalesSummary></table>
  </div>
  <div>
    <button type="submit" id="save">
      <i class="fas fa-save"></i> Save
    </button>
  </div>
</form>

但我没有得到结果。

我只有一个 JSON,当用户选择“类别”填充表格时,我想从中做所有事情来填充下拉列表和过滤器。

最佳答案

对于这个项目,分解步骤可能会更好。我看到了几个步骤:

  • 根据数据键创建表头
  • 根据数据创建表体
  • 根据类别名称更新过滤器选项(唯一)

考虑以下代码。

var tData = [{
    "Category name": "juce",
    "Category Data": [{
      "Item Code": "1234",
      "Item Name": "juce1",
      "Quantity": "0"
    }]
  },
  {
    "Category name": "juce",
    "Category Data": [{
      "Item Code": "1234",
      "Item Name": "juce2",
      "Quantity": "0"
    }]
  },
  {
    "Category name": "rice",
    "Category Data": [{
      "Item Code": "1234",
      "Item Name": "rice1",
      "Quantity": "0"
    }]
  },
  {
    "Category name": "rice",
    "Category Data": [{
      "Item Code": "1234",
      "Item Name": "juce2",
      "Quantity": "0"
    }]
  },
  {
    "Category name": "roti",
    "Category Data": [{
      "Item Code": "1234",
      "Item Name": "roti1",
      "Quantity": "0"
    }]
  },
  {
    "Category name": "roti",
    "Category Data": [{
      "Item Code": "1234",
      "Item Name": "juce2",
      "Quantity": "0"
    }]
  }
];

$(function() {
  function getCatNames(arr) {
    var names = [];
    $.each(arr, function(key, obj) {
      names.push(obj['Category name']);
    });
    var unique = names.filter((v, i, a) => a.indexOf(v) === i);
    return unique;
  }

  function updateFilter(obj, d) {
    var catOpts = getCatNames(d);
    obj.html("");
    obj.append("<option>All</option>");
    $.each(catOpts, function(k, v) {
      $("<option>").html(v).appendTo(obj);
    });
  }

  function filterSelection(obj) {
    var s = $("#CategoryName option:selected").val();
    if (s == "All") {
      $("tbody tr", obj).show();
      return;
    }
    $("tbody tr", obj).each(function(ind, el) {
      var cat = $("td:eq(0)", el).text().trim();
      if (cat != s) {
        $(el).hide();
      } else {
        $(el).show();
      }
    });
  }

  function makeTableHead(obj, data) {
    if (obj.find("thead").length === 0) {
      $("<thead>").prependTo(obj);
    }
    var row = $("<tr>").appendTo($("thead", obj));
    $.each(data[0], function(k, v) {
      console.log(k, v);
      if (k == "Category name") {
        $("<th>", {
          class: "text-center head"
        }).html(k).appendTo(row);
      } else {
        $.each(v[0], function(j, x) {
          $("<th>", {
            class: "text-center head"
          }).html(j).appendTo(row);
        });
      }
    });
  }

  function makeTableBody(obj, data, qnty) {
    if (qnty == undefined) {
      qnty = true;
    }
    if (obj.find("tbody").length === 0) {
      $("<tbody>").appendTo(obj);
    }
    $.each(data, function(k, v) {
      var row = $("<tr>", {
        class: "item-" + k
      }).appendTo($("tbody", obj));
      var n = $("<td>", {
        class: "text-center cat-name"
      }).html(v['Category name']).appendTo(row);
      $("<input>", {
        type: "hidden",
        name: "cat-name[]",
        value: v['Category name']
      }).appendTo(n);
      var itc = $("<td>", {
        class: "text-center item-code"
      }).appendTo(row);
      itc.html(v['Category Data'][0]['Item Code']);
      $("<input>", {
        type: "hidden",
        name: "item_code",
        value: v['Category Data'][0]['Item Code']
      }).appendTo(itc);
      var itn = $("<td>", {
        class: "text-center item-name"
      }).appendTo(row);
      itn.html(v['Category Data'][0]['Item Name']);
      $("<input>", {
        type: "hidden",
        name: "item_name",
        value: v['Category Data'][0]['Item Name']
      }).appendTo(itn);
      if (qnty) {
        var q = $("<td>", {
          class: "cat-qnty"
        }).appendTo(row);
        $("<input>", {
          name: "Quantity",
          autocomplete: "on",
          value: v['Category Data'][0].Quantity,
          type: "number",
          class: "dataReset"
        }).css({
          border: "none",
          "text-align": "center",
          width: "4em"
        }).appendTo(q);
      }
    });
  }

  function addTable(tableData, tbl) {
    if (tbl == undefined) {
      tbl = $("<table>", {
        id: "HourlysalesSummary"
      });
    }
    //var col = Object.keys(tableData[0]);
    //var countNum = col.length;
    makeTableHead(tbl, tableData);
    makeTableBody(tbl, tableData);
    var divContainer = $("#HourlysalesSummary").parent();
    divContainer.html(tbl);
    tbl.addClass("table table-striped table-bordered table-hover");
  }

  updateFilter($("#CategoryName"), tData);
  addTable(tData, $("#HourlysalesSummary"));

  $("#CategoryName").change(function() {
    filterSelection($("#HourlysalesSummary"));
  });
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="www.google.com" id="form1">
  <div class="row position-relative">
    <div class="col-lg-4">
      <h5 id="commonHeader">Category</h5>
      <select class="test" id="CategoryName" name="categoryCode">
        <option>All</option>
        <option>juce</option>
        <option>rice</option>
        <option>roti</option>
      </select>
    </div>
  </div>
  <hr style="border: 1px solid black">
  <div class="table-responsive">
    <table class="w-100" id="HourlysalesSummary">
      <thead></thead>
      <tbody></tbody>
    </table>
  </div>
  <div>
    <button type="submit" id="save"><i class="fas fa-save"></i> Save</button>
  </div>
</form>

如您所见,我创建了以下函数:

  • addTable( data )
    • makeTableHead( object, data, quantity )
    • makeTableBody( object, data, quantity )
  • updateFilter( object, data )
    • getCatNames( data )
    • filterSelection( object )

利用<thead><tbody>当您有更多动态表体内容时可以提供帮助。如果您进行更改或加载新数据,您可能只需要运行 makeTableBody($("#HourlysalesSummary"), tData);使用新数据。

我将您的很多代码切换到了 jQuery。如果可能的话,我不喜欢混合。这也让我们可以使用 $.each()更多,这对数组和对象数据非常有帮助。

希望这对您有所帮助。

关于javascript - 尝试制作 HTML 表格并使用相同的 JSON 数据填充选择标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54333009/

相关文章:

javascript - 我可以查看浏览器的事件循环来了解 JS 的执行顺序吗?

javascript - 如何使用 Electron 运行 Aurelia 应用程序?

javascript - 如何以动态形式应用动态蒙版?

jquery - 将 <a> 点击事件作为 Google Analytics 事件处理

html - google搜索时的网页描述

javascript - ShadowDOM 与文档片段——它们有何不同?

javascript - Algolia 搜索结果覆盖了 css 格式

javascript - printJS - 为什么打印 PDF 文件时请求的 URL 未找到错误?

javascript - 返回语法错误

javascript - 在数组值之间的范围内发生某些行为吗?