I have the following function:
function initPaymentBlock(bIdx) {
var paymentType = 'default';
if( $('#gc-apply-btn-'+bIdx).length ) {
$('#gc-apply-btn-'+bIdx).click( function() {
poApplyGiftCard(bIdx);
console.log("about to change payment type");
paymentType = 'credit card';
console.log("paymentType inside function: " + paymentType);
});
}
console.log("payment type: " + paymentType);
poGetPaymentOption(paymentType, 0, bIdx);
}
The paymentType variable is set to 'default' inside the initial statement. Inside the internal click function, it's changed to 'credit card'. When I run the console.log statement inside the internal function, it returns credit card. The console.log outside the internal function (right before the poGetPaymentOption call) returns 'default'.
I know the issue is the scope of the variable, but can't figure out how or where I can set it so that the poGetPaymentOption function call gets the correct value ('default' if the button isn't clicked before it's run; 'credit card' if the button is clicked.) Can someone help me out?
2 Answers 2
Its pretty obvious. The click changes the value but only after the click. Your second console log runs before a click event is fired. What is wrong with this?
function initPaymentBlock(bIdx) {
var paymentType = 'default';
if( $('#gc-apply-btn-'+bIdx).length ) {
$('#gc-apply-btn-'+bIdx).click( function() {
poApplyGiftCard(bIdx);
console.log("about to change payment type");
paymentType = 'credit card';
console.log("paymentType inside function: " + paymentType);
poGetPaymentOption(paymentType, 0, bIdx);
});
}
}
Comments
There is no issue with scope. It's all about the order of execution.
Here is how the code executes:
- When you enter the initPaymentBlock function, you set it to 'default'.
- Then you create a click handler that will change its value to 'credit card', but ONLY AFTER somebody clicks a button.
- Then your console output at the bottom puts out the current value, which is still 'default'.
- Now, if the user clicks the button, the click handler will execute and it will output 'credit card'
Here is the expected console output when you run initPaymentBlock():
- payment type: default
That's it. Now when you click the button, the following output will show:
- about to change payment type
- paymentType inside function: credit card
5 Comments
initPaymentBlock function. It never executes again after the button click.
poGetPaymentOptioninside the click event? It really depends on what you are trying to do and WHEN you are trying to do it.paymentTypewill always be its initial value whenpoGetPaymentOptiongets run because it can't change until someone clicks something, and from what you just saidpoGetPaymentOptiongets run wheninitPaymentBlockgets run.