Jack Billy
Jack Billy

Reputation: 7211

Adding function parameters using a single variable in jQuery

I was thinking the is it possible to pass a variable to function which is to be executed on clicking the button and the function is given by a variable.

Also the parameters of the functions could be more than one and so I separated them by ,.

So is there a way that I can put the parameters into function using any jQuery plugin or a function. Please help me out, cause I'm confuse big time! Here is my current jQuery Code:

function Func (a,b){
 alert(a+' | '+b);   
}
var Parameters = 'cool,123';
var Function = Func;

$('button').click(Function);

Problem demo

Thanks in advance

Upvotes: 1

Views: 1158

Answers (4)

Hogan
Hogan

Reputation: 70538

Here is another way to do it, I like this better myself because it is somewhat self documenting. Each of the "parameters" in the options list has a name.

This is a common design pattern in JavaScript libraries for options to a module.

function Func (c){
 alert(c.a+' | '+c.b);   
}
var Parameters = { a : "cool", b: 123 };
var Function = Func;

$('button').click(Parameters );

Upvotes: 1

karim79
karim79

Reputation: 342695

Is this what you're after?

function Func (a,b){
 alert(a+' | '+b);   
}
var Parameters = 'cool,123';

$('button').click(function() {
    Func.apply(this, Parameters.split(","));
});

Demo: http://jsfiddle.net/6nJx7/14/

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/function/apply

Upvotes: 2

DarthJDG
DarthJDG

Reputation: 16591

You can use function.apply(). Pass your list of parameters in as an array and you can even set a scope if you wish to do so:

function myFunc(a,b){
    alert(a+", "+b);
}

var args = ["one", "two"];
var func = myFunc;

$('button').click(function(){
    func.apply(this, args);
});

Upvotes: 3

bleeeah
bleeeah

Reputation: 3604

You could pass your parameters as an array ..

 function Func (a){
     alert(a[0]+' | '+a[1]);   
    }
    var Parameters = new Array(0,1);
    var Function = Func;

    $('button').click(Function(Parameters));

Upvotes: 1

Related Questions