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.
$(".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);
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>