Reputation: 45
JavaScript novice here....I need to call a JavaScript function that is passed two variables. I then need those 2 variables to be passed to another function via an onClick event. Here is the general idea:
function FirstFunction(var1, var2) {
// Using console.log to verify passed variables
console.log(uid);
console.log(accessToken);
$('#dialog-message').html('<div><button onclick="SecondFunction(var1, var2)">Submit</button></div>');
};
function SecondFunction(var1, var2) {
// Using console.log to verify passed variables
console.log(uid);
console.log(accessToken);
};
I am unable to see var1 & var2 in SecondFunction(). What's wrong here?
Upvotes: 0
Views: 884
Reputation: 816442
My original comment:
The inline click event handler will be evaluated in global scope, not inside the function scope. It look like you are using jQuery, so use it to create the DOM elements and bind the event handler.
This way, you can avoid the whole problem (and don't have to use global variables):
function FirstFunction(var1, var2) {
var $button = $('<button />', {
click: function() {
SecondFunction(var1, var2);
},
text: 'Submit'
});
$('<div />').append($button).appendTo('#dialog-message');
}
Because now the event handler is a closure with access to var1
and var2
.
Upvotes: 1
Reputation: 695
Try
$('#dialog-message').html('<div><button onclick="SecondFunction(' + var1 +', ' + var2 + ' )>Submit</button></div>');
Upvotes: 0
Reputation: 1156
Try this
$('#dialog-message').html('<div><button onclick="SecondFunction('+ var1 + ','+ var2+ ')">Submit</button></div>');
Upvotes: 0