Reputation: 25
I try to send a javascript function 2 parameters like this:
var par1;
var par2;
$('#somediv').append('<div onclick="somefunction('+par1+','+par2+');"></div>');
i'm creating a lot of divs like this one and all dynamicaly, i just need to find the correct way to pass the par1 and par2 to the operate them later.
right now only par1 is ok, par2 is undefined (they both has string value).
Any suggestions?
Upvotes: 0
Views: 4154
Reputation: 1
perimeterBox
is function here
var perimeterBox = function(length,width)
{
return length+length+width+width;
};
perimeterBox(5,5);
Upvotes: 0
Reputation: 88845
Use jQuery onclick
e.g.
var par1 = 'par1';
var par2 = 'par2';
$('<div>Click</div>').appendTo('#somediv').click(function(){
somefunction(par1, par2)
})
function somefunction(v1, v2){
alert(v1+" "+v2);
}
See it in action http://jsfiddle.net/anuraguniyal/gjz72
But it depends from where you are getting par1 and par2, if they are related to div and you need to have different one for each div, you should add them in html as data attribute e.g.
$('<div data-par1="par1" data-par2="par2" >Click</div>').appendTo('#somediv').click(somefunction)
function somefunction(){
alert($(this).attr('data-par1')+" "+$(this).attr('data-par2'));
}
See it in action http://jsfiddle.net/anuraguniyal/gjz72/14/
Upvotes: 1
Reputation: 17024
The correct way to do fancy stuff like this is using .live
, .delegate
, or .on
in jQuery.
var par1; // assuming these get values at some point
var par2; // assuming these get values at some point
$('#somediv').append('<div class='fancyDiv'></div>');
$('#somediv').on("click", ".fancyDiv", function() {
someFunction(par1, par2);
}))
// use delegate instead of on if you're in jQuery 1.6 or lower
$('#somediv').delegate(".fancyDiv", "click", function() {
someFunction(par1, par2);
}))
Upvotes: 2