Modifying a json collection within jquery
I have a list of invoices displayed on the screen. Right now, a user can select or unselect an invoice with a checkbox or change the amount they would like to pay. When this happens, the total amount to be paid for all invoices is being summed up and displayed.
The ultimate goal here is to keep track of an array of arrays of data, which comes from the server. I'm using json because it is standardized.
Then I have a hidden with json data like so:
<input id="InvoicingGridRows" name="InvoicingGridRows" type="hidden"
value="[[{"Value":"TST-1000"},{"Value":346.230000},
{"Value":null},{"Value":null},{"Value":null},
{"Value":null}],
[{"Value":"TST-1001"},
{"Value":126.970000},{"Value":null},{"Value":null},
{"Value":null},{"Value":null}]]" />
Right now, the data has a lot of empty placeholders for data.
What I am trying to do is create a javascript object so that when the events happen above that cause the summation to occur, I can initiate targeted edits/deletes/adds. Here;s what I have so far.
var invoiceRows = function () {
var targetControl = '';
var getByInvoiceId = function (invoiceId) {
var data = $(targetControl.val());
for (var x = 0; x < data.leng开发者_开发知识库th; x++) {
if (data[x][0].Value == invoiceId)
return data[x];
}
return null;
};
return {
init: function (selector, invoices) {
targetControl = $(selector);
//set up the gridrows to defaulted values
targetControl.val(invoices);
},
save: function (invoiceId, amount) {
var invoiceData = getByInvoiceId(invoiceId);
if (invoiceData) {
//update
} else {
//add new
}
},
remove: function (invoiceId) {
//remove row with invoiceid
}
}
} ();
My question is how do I easily modify/delete rows as well as add new rows into my json object, and then save it back into the hidden field? Is that even possible or is there a better way? I'm open to suggestions.
You can convert the string in the hidden input into a javascript object by using eval
:
var dataObj = eval($("#InvoicingGridRows").val());
I'd do this only once, and then do all your operations such as remove on this object. When you're ready to send it back to the server, convert the object back into a string:
var dataStr = JSON.stringify(dataObj);
$("#InvoicingGridRows").val(dataStr);
Alternatively, if you can modify how your server works, get the server to create a <script>
tag containing the data ready for use as a javascript object - basically the string in the hidden input, but without the quotes around the whole thing and with a variable assignment in front of it. E.g. get your server to output:
<script type="text/javascript">
var dataObj = {...};
</script>
No need for eval()
now.
精彩评论