如何将输入数据添加到隐藏的输入字段中

时间:2016-11-13 10:50:49

标签: javascript jquery json

我有一个输入字段,用户输入所需的输入,并将数据复制到隐藏的输入字段,但新数据替换旧数据时会出现问题

这是我复制所有数据的地方

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

这是输入字段

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

现在,如果我添加像&#39;你好&#39;然后它被添加到隐藏的输入值然后它看起来像

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

现在如果再次进入&#39;你好吗&#39;然后它用new ..替换旧数据。

我想保留两个数据

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

2 个答案:

答案 0 :(得分:0)

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。希望你得到所需的输出。

答案 1 :(得分:0)

假设您有一些方法可以知道何时添加新数据,并且您的data是一个数组,这可以通过先检索该值然后将新数据推送到堆栈来实现。例如:

&#13;
&#13;
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()));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="ApCount" id="ap" value="">
&#13;
&#13;
&#13;