【问题标题】:how to retain the text field value into the text field如何将文本字段值保留到文本字段中
【发布时间】:2019-01-25 04:06:58
【问题描述】:

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

  • 我得到的两列数据为json 这两个字段是itemNameitemCode,第三列是我自己创建的Quantity,我将其赋值为0
  • 我也有一个下拉列表,它是 category,其中有几个下拉列表第一个是 All,最初它显示所有数据
  • 之后,如果用户点击juice 类别,则只会填充果汁项目
  • 然后用户在那里输入一些数量并且没有保存就转到另一个类别比如rice 并在那里输入一些数量
  • 在此之后,当用户返回 juice 类别时,他输入的数量全部消失,并显示为 0,这是我不想要的

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

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

$(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 的初始值

请大家帮帮我..我被困在这里很久了..没有得到任何 idia 我怎么能做到这一点。 我应该在ui endserver end 上做,但数量不是来自后端,这就是我在客户端创建它的原因

请大家提供任何类型的指导,如你应该这样做,你应该这样做,这将非常有帮助

【问题讨论】:

  • 您要保留输入的值还是只保留实际会话的值?
  • @PabloDarde 我不知道哪个会更好,因为我对此很陌生..当用户点击保存时,无需存储价值
  • 您可以监听输入字段的更改,然后在进行更改时将值存储在本地存储中。例如 localStorage.setItem('juiceQuantity', juiceQuantity);然后每次选择一个类别时,首先检查本地存储以查看是否存在值,如果存在则将该值插入到输入字段中。
  • 您能否发布一个 tableData 示例(例如果汁类别),以便我尝试一下?
  • @sarah 假设用户点击果汁然后“[{“商品代码”:“1056”,“商品名称”:“香蕉奶昔”,},{“商品代码”:“2883” , "项目名称": "芒果奶昔", }, { "项目代码": "1664", "项目名称": "苹果汁", }, { "项目代码": "2705", "项目名称": "草莓奶昔", }, ] 对其他人相同,数据格式也相同,只是名称已更改

标签: javascript jquery html


【解决方案1】:

根据我们在 cmets 中的讨论,我想出了另一个解决您问题的方法。

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

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

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

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

然后,当生成表时(在addTable 函数中),您添加一个名为item-row 的类以及一个等于 JSON 中的"category name" 的类(因此以类似于以下方式生成 tr 标签格式):

<tr class="item-row juce">

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

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

element.style.visibility = "visible";

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

【讨论】:

【解决方案2】:

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

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

这里有一个关于如何在项目中使用它的想法。

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

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

另外,您可以通过访问Developer tools 中的Application 选项卡来查看localStorage 中的内容(我在代码下方附上了屏幕截图)。

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

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

【讨论】:

  • 我在将这个添加到我的代码时遇到了一些问题。如果你有空请告诉我。
  • @dheerajkumar 我改变了答案,因为我意识到存在问题。请完整阅读它,因为它与以前有很大不同。如果您有任何问题,请告诉我
  • 嘿..你的代码真的帮助了我,但我有一个很小的问题,只要你有空闲时间请在这里评论,我想澄清一个小疑问
  • @dheerajkumar 确定没有问题。它是什么? :)
  • 嘿,现在我将值存储到局部变量中,所以保存表单我想将表数据保存到 db..但目前它只保存当前页面数据......就像用户输入也有一些果汁和米饭,我在点击米饭选项时保存数据..它只是保存米饭数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多