javascript - 如何在单击按钮时显示新的 HTML 表格

标签 javascript jquery html

我有一个动态的 HTML 表格。我正在使用 JSON 数据创建它。 我在一张表上工作时有几个要求。

有一个按钮view,如果用户单击它,它会显示所有非零行,但目前它显示在我不想要的同一个表中。

我想要实现的目标

  • 当用户点击查看时,新表格应并排填充或在主表格下方填充
  • 我已经使用非零行数据过滤了现有表
  • 现在,我尝试通过单击查看将该数据填充到新表中
  • 此用户可以看到他输入的内容并可以重新检查他输入的记录

代码片段

var tableData = [{
    "Item Code": "1978",
    "Item Name": "Alu Chat-S",
    "Category Name": "Chats"
  },
  {
    "Item Code": "1979",
    "Item Name": "Dahi Alu Chat-S",
    "Category Name": "Chats"
  },
  {
    "Item Code": "1980",
    "Item Name": "Samosa-S",
    "Category Name": "Chats"
  },
  {
    "Item Code": "1981",
    "Item Name": "SamosaChat-S",
    "Category Name": "Chats"
  },
  {
    "Item Code": "1982",
    "Item Name": "Dahi Samosa Chats-S",
    "Category Name": "regular"
  },
  {
    "Item Code": "1983",
    "Item Name": "Garam Samosa Chats-S",
    "Category Name": "regular"
  },
  {
    "Item Code": "1984",
    "Item Name": "Kachori Chats-S",
    "Category Name": "regular"
  },
  {
    "Item Code": "1985",
    "Item Name": "Garam Kachori Chat-S",
    "Category Name": "regular"
  },
  {
    "Item Code": "1986",
    "Item Name": "Dahi Kachori Chat-S",
    "Category Name": "fastfood"
  },
  {
    "Item Code": "1987",
    "Item Name": "Dai Raj Kachori-S",
    "Category Name": "fastfood"
  },
  {
    "Item Code": "1988",
    "Item Name": "Baby Kachori Chat-S",
    "Category Name": "fastfood"
  },
  {
    "Item Code": "1989",
    "Item Name": "Dahi Baby Kachori-S",
    "Category Name": "fastfood"
  },
  {
    "Item Code": "1990",
    "Item Name": "Anar Bhalla-S",
    "Category Name": "fastfood"
  },
  {
    "Item Code": "1991",
    "Item Name": "Dahi Bhalla-S",
    "Category Name": "fastfood"
  },
  {
    "Item Code": "1992",
    "Item Name": "Jhal Muri-S",
    "Category Name": "fastfood"
  },
  {
    "Item Code": "1993",
    "Item Name": "Chat Platter-S",
    "Category Name": "fastfood"
  },
  {
    "Item Code": "1994",
    "Item Name": "Dahi Papdi Chat-S",
    "Category Name": "GIFT PACK"
  },
  {
    "Item Code": "2402",
    "Item Name": "ALMOND CHBAR",
    "Category Name": "GIFT PACK"
  },
  {
    "Item Code": "333",
    "Item Name": "A BR SB EX",
    "Category Name": "EXEMPTED"
  },
  {
    "Item Code": "603",
    "Item Name": "AMUL FRESH CREAM",
    "Category Name": "EXEMPTED"
  }
]

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);
    tr.classList.add("item-row");
    for (var j = 0; j < col.length + 1; j++) {
      //here i am adding a class with the name of the category to each items row.
      var categoryName = tableData[i]["Category Name"];
      tr.dataset.category = categoryName;

      let tabCell = tr.insertCell(-1);
      var hiddenField = document.createElement("input");
      hiddenField.style.display = "none";
      var quantityField = document.createElement("input");
      var tabledata = tableData[i][col[j]];
      if (i > -1 && j >= colNum) {

        quantityField.style.border = "none";
        quantityField.style["text-align"] = "right";
        quantityField.setAttribute("name", "Quantity");
        quantityField.setAttribute("autocomplete", "on");
        quantityField.setAttribute("value", "0");
        quantityField.setAttribute("type", "number");
        quantityField.setAttribute("required", "required");
        quantityField.classList.add("dataReset");
        quantityField.toLocaleString('en-IN');
        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 (tableData[i]["Category Name"] === tableData[i][col[j]]) {
          tabCell.innerHTML = tabledata;
          hiddenField.setAttribute("name", "Category_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);
var selectedOption = "";
$("#CategoryName").on("change", function() {
  selectedOption = this.value;
  console.log(selectedOption);
  //getting all item rows so i can target them.
  var itemRows = document.getElementsByClassName("item-row");

  if (selectedOption === "All") {
    //If "All" then style all rows with visibility: visible.
    for (var i = 0; i < itemRows.length; i++) {
      itemRows[i].style.visibility = "visible";
    }
  } else {
    //If the selectedOption is anything other than "All",
    // firstly i am style all rows with visibility: collapse
    for (var i = 0; i < itemRows.length; i++) {
      itemRows[i].style.visibility = "collapse";

    }
    /* alert(itemRows); */
    // then getting all rows which have the selectedOption as a class and style those rows with visibility: visible.
    var selectedItemRows = document.querySelectorAll("[data-category='" + selectedOption + "']");

    for (var i = 0; i < selectedItemRows.length; i++) {
      selectedItemRows[i].style.visibility = "visible";
    }
  }

});

function view() {
  //get all quantity input fields
  var quantityFields = document.getElementsByClassName("dataReset");
  //iterate through all quantity input fields
  for (var i = 0; i < quantityFields.length; i++) {
    if (quantityFields[i].value != 0) {
      //if the input value of this quantity field is not equal to zero then find the closest "item-row"
      //so that we can set this table row to visible
      quantityFields[i].closest(".item-row").style.visibility = "visible";
    } else {
      //if the input value of this quantity field is equal to zero then find the closest "item-row"
      //so that we can set this table row to collapse
      quantityFields[i].closest(".item-row").style.display = "none";
    }
  }
  //change the value of the select menu to "All"
  $('#CategoryName').val('All');
  $('#see').hide();
  $('#edit').show();


}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<div class="container" id="divHide">
  <form id="indentForm" autocomplete="on">
    <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>Chats</option>
          <option>regular</option>
          <option>fastfood</option>
          <option>GIFT PACK</option>
          <option>EXEMPTED</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">
					 Save
				</button>
      <button id="see" type="button" onclick="view()">view</button>


    </div>
  </form>
</div>

我还尝试了另一种方法,当用户单击“查看”时,“查看”按钮将更改为“编辑”,并且表格会填充非零行,但当用户单击“编辑”时,再次我的表数据重置为 0,我曾经并且正在使用 autocomplete=on 来实现此目的,但是单击编辑后,它只是将我的表数据刷新为 0

所以这没有成功。现在我有了一个新想法,即并排填充一个表以进行查看,另一个进行编辑,只是面临着单击非零数据​​的查看按钮来创建新表的问题。

注意

我在尝试的每种方法中面临的主要问题是为什么当用户单击查看按钮时数据会重置为零。

最佳答案

您需要创建第二个表并将所需的行克隆到该表中。

所以你可以像这样添加一个新表:

<!-- Add a new table for results -->
<div class="table-responsive">
  <table class="w-100" id="table-result"></table>
</div>

循环遍历非空字段:

var quantityFields = $(".dataReset").filter(function() {
    return this.value!=0;
});

克隆该行,将其添加到新表中并重置第一个表中的行:

let row = Object.assign(quantityFields[i].closest(".item-row"));
tResult.append(row);

for (var i = 0; i < quantityFields.length; i++) {
  //COPY CURRENT ROW IN NEW TABLE
  let row = $(quantityFields[i].closest(".item-row")).clone();
  tResult.append(row);
  //RESET THE CURRENT VALUE IN FIRST TABLE
  quantityFields[i].value="0";
//}

}

看看这是否适用于您的代码:

var tableData = [{
    "Item Code": "1978",
    "Item Name": "Alu Chat-S",
    "Category Name": "Chats"
  },
  {
    "Item Code": "1979",
    "Item Name": "Dahi Alu Chat-S",
    "Category Name": "Chats"
  },
  {
    "Item Code": "1980",
    "Item Name": "Samosa-S",
    "Category Name": "Chats"
  },
  {
    "Item Code": "1981",
    "Item Name": "SamosaChat-S",
    "Category Name": "Chats"
  },
  {
    "Item Code": "1982",
    "Item Name": "Dahi Samosa Chats-S",
    "Category Name": "regular"
  },
  {
    "Item Code": "1983",
    "Item Name": "Garam Samosa Chats-S",
    "Category Name": "regular"
  },
  {
    "Item Code": "1984",
    "Item Name": "Kachori Chats-S",
    "Category Name": "regular"
  },
  {
    "Item Code": "1985",
    "Item Name": "Garam Kachori Chat-S",
    "Category Name": "regular"
  },
  {
    "Item Code": "1986",
    "Item Name": "Dahi Kachori Chat-S",
    "Category Name": "fastfood"
  },
  {
    "Item Code": "1987",
    "Item Name": "Dai Raj Kachori-S",
    "Category Name": "fastfood"
  },
  {
    "Item Code": "1988",
    "Item Name": "Baby Kachori Chat-S",
    "Category Name": "fastfood"
  },
  {
    "Item Code": "1989",
    "Item Name": "Dahi Baby Kachori-S",
    "Category Name": "fastfood"
  },
  {
    "Item Code": "1990",
    "Item Name": "Anar Bhalla-S",
    "Category Name": "fastfood"
  },
  {
    "Item Code": "1991",
    "Item Name": "Dahi Bhalla-S",
    "Category Name": "fastfood"
  },
  {
    "Item Code": "1992",
    "Item Name": "Jhal Muri-S",
    "Category Name": "fastfood"
  },
  {
    "Item Code": "1993",
    "Item Name": "Chat Platter-S",
    "Category Name": "fastfood"
  },
  {
    "Item Code": "1994",
    "Item Name": "Dahi Papdi Chat-S",
    "Category Name": "GIFT PACK"
  },
  {
    "Item Code": "2402",
    "Item Name": "ALMOND CHBAR",
    "Category Name": "GIFT PACK"
  },
  {
    "Item Code": "333",
    "Item Name": "A BR SB EX",
    "Category Name": "EXEMPTED"
  },
  {
    "Item Code": "603",
    "Item Name": "AMUL FRESH CREAM",
    "Category Name": "EXEMPTED"
  }
]

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);
    tr.classList.add("item-row");
    for (var j = 0; j < col.length + 1; j++) {
      //here i am adding a class with the name of the category to each items row.
      var categoryName = tableData[i]["Category Name"];
      tr.dataset.category = categoryName;

      let tabCell = tr.insertCell(-1);
      var hiddenField = document.createElement("input");
      hiddenField.style.display = "none";
      var quantityField = document.createElement("input");
      var tabledata = tableData[i][col[j]];
      if (i > -1 && j >= colNum) {

        quantityField.style.border = "none";
        quantityField.style["text-align"] = "right";
        quantityField.setAttribute("name", "Quantity");
        quantityField.setAttribute("autocomplete", "on");
        quantityField.setAttribute("value", "0");
        quantityField.setAttribute("type", "number");
        quantityField.setAttribute("required", "required");
        quantityField.classList.add("dataReset");
        quantityField.toLocaleString('en-IN');
        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 (tableData[i]["Category Name"] === tableData[i][col[j]]) {
          tabCell.innerHTML = tabledata;
          hiddenField.setAttribute("name", "Category_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);
var selectedOption = "";
$("#CategoryName").on("change", function() {
  selectedOption = this.value;
  console.log(selectedOption);
  //getting all item rows so i can target them.
  var itemRows = document.getElementsByClassName("item-row");

  if (selectedOption === "All") {
    //If "All" then style all rows with visibility: visible.
    for (var i = 0; i < itemRows.length; i++) {
      itemRows[i].style.visibility = "visible";
    }
  } else {
    //If the selectedOption is anything other than "All",
    // firstly i am style all rows with visibility: collapse
    for (var i = 0; i < itemRows.length; i++) {
      itemRows[i].style.visibility = "collapse";

    }
    /* alert(itemRows); */
    // then getting all rows which have the selectedOption as a class and style those rows with visibility: visible.
    var selectedItemRows = document.querySelectorAll("[data-category='" + selectedOption + "']");

    for (var i = 0; i < selectedItemRows.length; i++) {
      selectedItemRows[i].style.visibility = "visible";
    }
  }

});

function view() {

// Delete 2nd table contents
var tResult = $("#table-result");
tResult.empty();
  var quantityFields = $(".dataReset").filter(function() {
    return this.value!=0;
});
  //iterate through all quantity input fields
  for (var i = 0; i < quantityFields.length; i++) {
      //COPY CURRENT ROW IN NEW TABLE
      let row = $(quantityFields[i].closest(".item-row")).clone();
      tResult.append(row);
      //RESET THE CURRENT VALUE IN FIRST TABLE (commented out)
      // quantityFields[i].value="0";
    //}
  }
  //change the value of the select menu to "All"
  $('#CategoryName').val('All');
  $('#see').hide();
  $('#edit').show();


}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<div class="container" id="divHide">
  <form id="indentForm" autocomplete="on">
    <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>Chats</option>
          <option>regular</option>
          <option>fastfood</option>
          <option>GIFT PACK</option>
          <option>EXEMPTED</option>
        </select>
      </div>
    </div>
    <hr style="border: 1px solid black">
    <div class="table-responsive">
      <table class="w-100" id=HourlysalesSummary></table>
    </div>
    <!-- Add a new table for results -->
    <div class="table-responsive">
      <table class="w-100" id="table-result"></table>
    </div>
    <div>
      <button type="submit" id="save">
					 Save
				</button>
      <button id="see" type="button" onclick="view()">view</button>


    </div>
  </form>
</div>

关于javascript - 如何在单击按钮时显示新的 HTML 表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54416419/

相关文章:

javascript - location.href 不在 jquery 事件中重定向

javascript - $_POST ["g-recaptcha-response"],它存储在验证码 div 元素中的什么位置?如何使用 AJAX 处理 Recaptcha?

javascript - 返回大括号在 javascript 中意味着什么(例如 return { init : init} )

jquery - 居中表单动态添加元素保持居中?

jquery - Accordion 选择的数据无法正常工作

html - 在不使用边距的情况下删除 <p> 之间的间距?

javascript - 正则表达式 - JS 中的表单数据验证

javascript - 如何每 5 秒重新加载一次页面?

jquery定位?

c# - 在 Web 服务中使用带有外部 CSS 的 HTML 页面中的 iTextSharp 创建 PDF