如何将文本字段值保留到文本字段中

时间:2019-01-17 18:01:12

标签: javascript jquery html

我有一个html表,其中有3个字段,其中之一是可编辑的

    我获得的两列
  • 数据为json,这两个字段分别是itemNameitemCode,而第三列是我自己创建的Quantity值为0
  • 我还有一个下拉列表category,其中有多个下拉列表,第一个是All,最初显示的是所有数据
  • 此后,如果用户单击juice(属于类别),则仅填充果汁项目
  • 然后用户在此处输入一些数量,而没有保存就转到另一个类别,例如rice并在此也输入一些数量
  • 此后,当用户返回juice类别时,他输入的数量全部消失,并显示为0我不想要

我想显示用户输入的值,即使他/她进入任何其他类别并返回

  • 简单来说,我想保留输入后的用户值。
  • 我正在基于Category选择进行ajax调用以填充表中的数据

$(document).ready(function() {

  $.ajax({ //this ajax is populating for all categories

    url: "CategoryOlWiseFilter",
    method: "GET",
    dataType: "json",
    contentType: "application/json; charset=utf-8",

    success: function(tableData) {
      addTable(tableData);
    }
  });

  $('#CategoryName').on('change', function() {
    var selectedOption = this.value;
    $.ajax({ //this one will populate which category is selected
      async: true,
      url: "ItemCategoryWiseFilter",
      method: "POST",
      data: {
        categoryName: selectedOption,
      },
    });
    $.ajax({
      async: true,
      url: "ItemCategoryWiseFilter",
      method: "GET",
      dataType: "json",
      contentType: "application/json; charset=utf-8",
      success: function(tableData) {
        addTable(tableData);

      }
    });

  });


});

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");
}
<div class="container">
  <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></table>
    </div>
    <div>
      <button type="submit" id="save">
					<i class="fas fa-save"></i> Save
				</button>
      <button id="clear">
					<i class="fas fa-eraser"></i> Clear
				</button>
      <button id="print" type="button" onclick="printFunction()">
					<i class="fas fa-print"></i> Print
				</button>
    </div>
  </form>
</div>

我从后端得到的json是

    [{
    "Item Code": "1001",
    "Item Name": "Beverages",
  },
  {
    "Item Code": "2003",
    "Item Name": "Juices",
  },
  {
    "Item Code": "1004",
    "Item Name": "Soups",
  },
  {
    "Item Code": "2005",
    "Item Name": "Cookies",
  },
]

我在ui上创建的数量,因此我可以在下拉菜单更改时存储值

我只希望一旦用户输入了任何数量,即使用户转到其他下拉菜单并回来,该数量也应该存在

我必须始终赋予0的初始值

请大家帮我..我长期以来一直被困在这里..没有任何想法,我怎么能做到这一点。 我应该在ui end还是server end上做,但是数量不是来自后端,这就是我在客户端创建它的原因

请大家像您这样的任何指导,都应该这样做,这应该很有帮助

2 个答案:

答案 0 :(得分:0)

您可以使用本地存储来存储键/值对。

键/值对将一直保留在浏览器中,直到您将其删除(即使用localStorage.clear())。

关于如何在项目中使用它的想法。

  1. 每次用户更改数量输入字段(不保存它)时,您会将值存储在本地存储中。
  2. 为此,您需要向每个数量输入字段添加唯一的id属性,例如id="Qty1056"。 (1056是商品代码)。然后,在将“值”属性设置为0(例如quantityField.setAttribute('value', '0');)之前,您需要检查本地存储,以查看是否从用户上次更改此商品的数量起就保存了一个值。 (如果本地存储中不存在任何值,则将数量值设置为0。 如果该物料代码在本地存储区中存在一个值,则获取该值并将其设置为数量输入字段的值。)

我已将新代码添加到您的完整代码中。我添加的代码带有注释//ADDING NEW CODE和其他注释。

此外,您还可以通过访问localStorage中的Application标签来检查Developer tools中的内容(我已在代码下方附加了屏幕截图)。

$(document).ready(function() {
  //clear local storage. (Note: if you want the values to persist after u refresh browser then you should NOT clear local storage).
  localStorage.clear();
  //the rest of your (document).ready code goes here as normal
});

//Your addTable function. (It's mostly the same as you had. I've added comments where i've added code)
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('type', 'number');
        quantityField.setAttribute('required', 'required');
        quantityField.classList.add("dataReset");

        //ADDING CODE HERE
        //create a unique Id string for the quantity input field.
        //We will use a string e.g 'Qty' concantenated with the item code for this item (as it is unique).
        //So we will have something like 'Qty1056'
        var quantityIdString = 'Qty' + tableData[i]['Item Code'];
        //add the id attribute to the input field
        quantityField.setAttribute('id', quantityIdString);
        //check localStorage to see if a quantity value exists for this item code
        //the key will be something like 'Qty1056' (the same as the id of the quantity input field).
        if(localStorage.getItem(quantityIdString) === null){
          //this key does NOT exist in local storage 
          //therefore the user has not changed the value of this items quantity input field yet so set it to 0.
          quantityField.setAttribute('value', '0');
        }else{
          //this key DOES exist in local storage so get the value from local storage and 
          //set the value attribute of our quantity input field to it
          var quantityFromLocalStorage = localStorage.getItem(quantityIdString);  
          quantityField.setAttribute('value', quantityFromLocalStorage);    
        }
        //append the quantity field to the table cell
        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");
  //ADDING CODE HERE
  //Now that the table has been appended to the document we can add the listeners to the quantity input fields as follows.
  for (var i = 0; i < tableData.length; i++) {
    ///log the item code to check it
    console.log(tableData[i]['Item Code']);
    //pass in the item code to the addQuantityFieldListener function
    addQuantityFieldListener(tableData[i]['Item Code']);
  }
}

//ADDING CODE HERE
function addQuantityFieldListener(itemCode){
  /* This function adds an "input" listener to a quantity input field to check when a new quantity value 
   * is selected/entered by the user for a particular item.
   * Each time a new quantity is selected/entered we store the new value in local storage. 
   */
  //form the quantityIdString which will also be the key of the item in local storage
  var quantityIdString = 'Qty' + itemCode;
  var quantityInputField = document.getElementById(quantityIdString);
  //we listen for the "input" event which will occur when a new quantity value is selected/entered by the user on this quantity input field. 
  quantityInputField.addEventListener("input", function(){
      //store the most recent quantity value for this item in local storage as follows:
      localStorage.setItem(quantityIdString, quantityInputField.value);
  });
}

开发人员工具中“应用程序”选项卡的屏幕截图(显示本地存储键/值对)

enter image description here

答案 1 :(得分:0)

在我们的评论讨论之后,我为您的问题提出了另一种解决方案。

您不必在每次选择类别(并使用本地存储)时都生成新表,而是可以在表中显示所有类别数据,然后根据选择的类别来隐藏和显示表行。

这意味着用户选择的任何数量值都将保留在输入字段中(即使更改类别),因为输入字段将保留在DOM中。

首先,您需要将类别名称添加到JSON中的每个项目,即

{ "Item Code": "1056", "Item Name": "banana shake", "category name": "juce"}

然后,在生成表时(在addTable函数中,您将添加一个名为item-row的类,并在JSON中添加一个与"category name"相等的类(因此会在类似于以下格式):

<tr class="item-row juce">

注意:这样,我们就可以定位特定的行以动态添加样式。

选择新类别后,可以将样式动态添加到适当的行。我们可以用来隐藏和显示表行的样式是可见性属性,可以将其设置为visible(显示行)或折叠(隐藏行)。

element.style.visibility = "visible";

OR

element.style.visibility = "collapse";

因此请记住,您的代码将如下所示(我已在添加代码的地方添加了注释):

addTable函数

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);
    //add a class called "item-row" to the table row so that we can target all item rows 
    tr.classList.add("item-row");
    for (var j = 0; j < col.length + 1; j++) {
      //add a class with the name of the category to each items row. This will be either juce, rice or roti etc. 
      var categoryName = tableData[i]["category name"];
      tr.classList.add(categoryName);

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

CategoryName onchange函数

  $('#CategoryName').on('change', function() {
    var selectedOption = this.value;
    console.log(selectedOption);
    //get all item rows so we 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",
        //we firstly style all rows with visibility: collapse
        for(var i = 0; i < itemRows.length; i++){
            itemRows[i].style.visibility = "collapse";
        }
        //we then get all rows which have the selectedOption as a class and style those rows with visibility: visible.
        var selectedItemRows = document.getElementsByClassName(selectedOption);
        for(var i = 0; i < selectedItemRows.length; i++){
            selectedItemRows[i].style.visibility = "visible";
        }
    }
  });