2016-11-13 132 views
0

我在那裏用戶輸入所需的輸入,將數據複製到一個隱藏的輸入字段,但是當新數據替換舊數據如何輸入數據添加到隱藏輸入字段

這是出現問題的一個輸入字段我複製所有數據

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

這是輸入字段

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

現在,如果我添加數據,如「你好」,然後將其添加到隱藏的輸入值,那麼它看起來像

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

你可以共享運行的代碼? – sam

回答

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。希望你有理想的輸出。

+0

我從可編輯表格中獲取數據而不是輸入字段 –

+0

上面提到了一個輸入字段..你應該添加完整的場景。 –

+0

我告訴我正在將數據存儲到隱藏的輸入字段中 –

0

假設你有當添加新的數據知道的一些方法,你的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="">