jrutter
jrutter

Reputation: 3213

Output JSON from values in hidden inputs

Im trying to create a JSON object like this:

bta.addConversion({ "order_id": "", "date": "", "items": [
        { "item_id":"item1", "desc":"description", "amount":"$123.33", "quantity":"1" },
        { "item_id":"item2", "desc":"description 2", "amount":"$10.25", "quantity":"1" }
    ]});

Using these values:

<input id="InvItemId[0]" name="sku" value="M0215508" type="hidden">
<input id="InvItemname[0]" name="CommerceItem" value="4 Seasons Wine Club Whites (RO)" type="hidden">
<input id="InvItemPrice[0]" name="Sku" value="129.95" type="hidden">
<input id="InvItemQty[0]" name="CommerceItem" value="1" type="hidden">
<input id="InvItemId[1]" name="sku" value="C0429210" type="hidden">
<input id="InvItemname[1]" name="CommerceItem" value="Laetitia Vineyard Select Pinot Noir" type="hidden">
<input id="InvItemPrice[1]" name="Sku" value="273.99" type="hidden">
<input id="InvItemQty[1]" name="CommerceItem" value="1" type="hidden">
<input id="InvItemId[2]" name="sku" value="M0249908" type="hidden">
<input id="InvItemname[2]" name="CommerceItem" value="Top-Value American Reds" type="hidden">
<input id="InvItemPrice[2]" name="Sku" value="199.99" type="hidden">
<input id="InvItemQty[2]" name="CommerceItem" value="1" type="hidden">
<input id="InvItemSize" name="/atg/userprofiling/Profile" value="3" type="hidden">

With JavaScript, Ive gotten this far - but it feels a bit hacked together. So wondering if there is a better way to do this:

jQuery(document).ready(function() {

        var invItemId = $('#InvID').val();
        var invItemsize = $('#InvItemSize').val();
        var InvItems='';
        var InvItemPrices='';
        var InvQtys='';
        var InvCats='';

        for(var itemCount=0;itemCount<invItemsize;itemCount++){
            var InvItem =document.getElementById("InvItemId["+itemCount+"]").value ;
            var ItemPrice = document.getElementById("InvItemPrice["+itemCount+"]").value ;
            var ItemQty = document.getElementById("InvItemQty["+itemCount+"]").value ;
            var InvItemName = document.getElementById("InvItemname["+itemCount+"]").value ;

            var itemsList='{"item_id":"'+InvItem+'","desc:""'+InvItemName+'", "amount:"'+ItemPrice+'", "quantity":"'+ItemQty+'"},';
            console.log(itemsList);

        }

        });

Upvotes: 1

Views: 221

Answers (1)

ferrants
ferrants

Reputation: 631

Are those input elements in a form? If so, (and they probably should be) you can use jQuery's form serialization function.

http://api.jquery.com/serializeArray/ Target the form

$('#my-form').serializeArray()

And then iterate through the array to generate the exact object you need to.

Upvotes: 1

Related Questions