My apologies is this has been asked/answered elsewhere. I may not know the correct terminology to find the desired results.
I'm building a sort of web app and in one area a user clicks a button, where a variable is obtained from the number at the end of the button's ID and is then passed to other functions for use in further processing. The issue I'm running into is that each subsequent time similar buttons are clicked, the variables from prior clicks are still stored within those functions.
JavaScript is not my forte, so I built a small fiddle that demonstrates my issue on a much smaller scale. If you click "Submit 1" in the fiddle, then click ALERT CUST_NUM, an alert box will display the variable's value. But if you repeat that process with either Submit 1 or Submit 2 (then clicking the ALERT button again), rather than alert a single instance of the variable, it will show multiple alert boxes in turn. And so on if you click Submit 1, then ALERT CUST_NUM, then Submit2, etc, such that it'll alert the chain of variables in a series of windows. I was hoping someone might explain why this occurs, as I would have expected only a single instance of the variable to exist within the function, being overwritten each time.
Fiddle: https://jsfiddle.net/02wgh4L1/
HTML:
<button class="submit-btn1" id="test-button-1">
Submit 1
</button>
<br/>
<button class="submit-btn2" id="test-button-2">
Submit 2
</button>
<br/>
<button id="alert-btn">
ALERT CUST_NUM
</button>
JavaScript:
$(".submit-btn1").click(function(){
var cust_num = parseInt(this.id.replace('test-button-',''), 10);
testFunction(cust_num);
})
$(".submit-btn2").click(function(){
var cust_num = parseInt(this.id.replace('test-button-',''), 10);
testFunction(cust_num);
})
function testFunction(cust_num) {
$("#alert-btn").click(function(){
alert(cust_num);
})
}
CodePudding user response:
Every time you click on submit-btn1
or submit-btn2
, you are adding a new event handler with cust_num
baked in to alert-btn
. If you cleared the previous event handlers like in the following:
function testFunction(cust_num) {
$("#alert-btn").off();
$("#alert-btn").click(function(){
alert(cust_num);
})
}
Then you would have only one event handler.
CodePudding user response:
You have to store your variables outside the functions to make them global:
var cust_num1 = '';
var cust_num2 = '';
$(".submit-btn1").click(function(){
cust_num1 = parseInt(this.id.replace('test-button-',''), 10);
testFunction(cust_num1);
})
$(".submit-btn2").click(function(){
cust_num2 = parseInt(this.id.replace('test-button-',''), 10);
testFunction(cust_num2);
})
function testFunction(cust_num) {
$("#alert-btn").click(function(){
alert(cust_num);
})
}