1

I have a bunch of input elements which calls a function when clicked. They pass along a bunch of parameters with information about what was clicked.

Like so:

onClick="updateCart('product_id', 'product_name', 'product_price');"

Now I want to create a function which take these parameters and put them in an array.

var updateCart = function (product_type, product_id, cost_model_id, product_name, subscription_campaign, startup_campaign) {
    this.product_row = [];
};

How do I do this?

1
  • Read about arguments variable. Commented Jun 4, 2014 at 13:25

2 Answers 2

1

As said, the easiest way will be to use arguments variable, which will contain all passed parameters in array-like format. You should transform it to array as follows:

var updateCart = function() {
    this.product_row = Array.prototype.slice.call(arguments);
    // another way: this.product_row = [].slice.call(arguments);
};
Sign up to request clarification or add additional context in comments.

Comments

1
var updateCart = function (product_type, product_id, cost_model_id, product_name, subscription_campaign, startup_campaign) {
    this.product_row = [ product_type, product_id, cost_model_id, product_name, subscription_campaign, startup_campaign ];
};

Isn't that what you're looking for?

When retrieving the information you just use:

this.product_row[0]; //returns product_type

But if you need something more readable, use an object instead:

var updateCart = function (product_type, product_id, cost_model_id, product_name, subscription_campaign, startup_campaign) {
    this.product_row = { "productType": product_type, "productID": product_id, "costModelID": cost_model_id, "productName": product_name, "subscriptionCampaign": subscription_campaign, "startupCampaign": startup_campaign };
};

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.