2

I have a cart on my website and I need to let users easily change the quantity of items they have in their cart at a moment.

Here is the javascript code I have so far:

<script type="text/javascript" language="javascript">
    $(document).ready(function () {

        var items = [];

        $(".item").each(function () {
            var productKey = $(this).find("input[type='hidden']").val();
            var productQuantity = $(this).find("input[type='text']").val();
            items.addKey(productKey, productQuantity); ?
        });

        // 1. Grab the values of each ammount input and it's productId.

        // 2. Send this dictionary of key pairs to a JSON action method.

        // 3. If results are OK, reload this page.
    });
</script>

The comments I wrote are just guidelines for me on how to proceed.

Is there a way to add a key/pair element to an array of sorts? I just need it to have a key and value. Nothing fancy.

I wrote in an addKey() method just for illustrative purposes to show what I want to accomplish.

4 Answers 4

4
items[productKey] = productQuantity;
Sign up to request clarification or add additional context in comments.

Comments

1

In JavaScript, Arrays are Objects (typeof(new Array)==='object'), and Objects can have properties which can be get/set using dot- or bracket- syntax:

var a = [1,2,3];
JSON.stringify(a); // => "[1,2,3]"
a.foo = 'Foo';
a.foo; // => 'Foo'
a['foo']; // => 'Foo'
JSON.stringify(a); // => "[1,2,3]"

So in your case, you can simply the productQuantity value to the productKey attribute of the item array as such:

items[productKey] = productQuantity;
items[productKey]; // => productQuantity

Comments

0

You can add anonymous objects to the items array like:

items.push({
    key: productKey,
    quantity: productQuantity
});

Then access them later as items[0].key or items[0].quantity.

Comments

0

Also you can use JQuery.data method and like that you can also get rid of those hidden.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.