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?
2 Answers 2
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);
};
Comments
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 };
};
argumentsvariable.