簡體   English   中英

如何將輸入數據添加到隱藏的輸入字段中

[英]How to add input data into hidden input field

我有一個輸入字段,用戶可以在其中輸入所需的輸入,並將該數據復制到隱藏的輸入字段中,但是當新數據替換舊數據時會出現問題

這是我復制所有數據的地方

$('#ap').val(JSON.stringify(data));

這是輸入字段

<input type="hidden" name="ApCount" id="ap" value="">

現在,如果我添加像“ hello”這樣的數據,那么它將被添加到隱藏的輸入值中,那么它看起來像

<input type="hidden" name="ApCount" id="ap" value="hello"> 

現在如果再次輸入“你好嗎”,它將用新數據替換舊數據。

我想保持兩個數據一樣

1 - [{"ratio":"1","size":"S","quantity":"83"},{"ratio":"2","size":"M","quantity":"166"}]

2 - [{"ratio":"3","size":"M","quantity":"93"},{"ratio":"2","size":"M","quantity":"136"}]

這些上面的json數據應正確編號,並以隱藏值存儲

這是運行代碼

$('body').on('click', '.export-btn', function() {
  var $rows = $TABLE.find('tr:not(:hidden)');
  var headers = [];
  var data = [];

  // Get the headers (add special header logic here)
  $($rows.shift()).find('th:not(:empty)').each(function () {
    headers.push($(this).text().toLowerCase());
  });

  // Turn all existing rows into a loopable array
  $rows.each(function () {
    var $td = $(this).find('td');
    var h = {};

    // Use the headers from earlier to name our hash keys
    headers.forEach(function (header, i) {
      h[header] = $td.eq(i).text();   
    });

    data.push(h);
  });

  // Output the result
  $('#ap').val(JSON.stringify(data));
});
HTML Code

<input id="getVal" value="" />
<button id="addBtn">Add</button>

// Jquery Code

    var arrayData = [];
    $("#addBtn").on("click", function() {
        var currentData = $("#getVal").val();
        arrayData.push({
            "count": arrayData.length + 1,
            "data": currentData
        });
        console.log(arrayData);
    });

您將每次以Json格式在arrayData中獲得更新的jason。 希望你得到了期望的輸出。

假設您有某種方式知道何時添加新數據,並且您的data是一個數組,則可以通過首先獲取值然后將新數據推入堆棧來實現。 例如:

 var data = [ [{"ratio":"1","size":"S","quantity":"83"}, {"ratio":"2","size":"M","quantity":"166"}] ]; var $apField = $('#ap'); $apField.val(JSON.stringify(data)); // sometime later on, you have an additional bit of data // let's say this is inside of an event handler that has // constructed this data for you: var newData = [{"ratio":"3","size":"M","quantity":"93"},{"ratio":"2","size":"M","quantity":"136"}]; // Now add it to the data already in the element var newDataSet = JSON.parse($apField.val()); // get the existing data newDataSet.push(newData); // add the new set $apField.val(JSON.stringify(newDataSet)); // update the field. console.log(JSON.parse($apField.val())); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="hidden" name="ApCount" id="ap" value=""> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM