Reputation: 19
I have this problem in jQuery:
I have a button that when clicked calls a function to create a div with an incremental id, equal to the number of clicks made. Here's my simplified solution:
$(document).ready(function() {
var count = 0;
});
$("#button").click(function() {
count = count + 1;
addDiv(count);
});
But, if I define the function click
here, the id on my div is NaN
while if I put the function of click
in document.ready()
, it creates two divs. I only want to create a div with incremental Id for each click!
Upvotes: 0
Views: 670
Reputation: 1
It's a scope problem. If you don't want to expose variables to the outer scope, you can use a closure.
let addDiv = function(){
let counter = 0;
return function(){
counter++;
let wrapper = $("#someDiv");
wrapper.append(`<div> id: ${counter}</div>`)
}
}();
button.on("click", function(){
addDiv();
});
Upvotes: 0
Reputation: 182
This was due to scope issue. Try this code:
$( document ).ready(function() {
var count =0;
console.log(count);
$( "#button" ).click(function() {
count=count+1;
addDiv(count);
});
});
Upvotes: 1
Reputation: 357
if you define a variable within a function, it is restricted only to this function, if you set it to a global scope, which is what you need in this case, the variable becomes available for all functions that are under this scope, look:
//global scope
var count = 0;
$( "#button" ).click(function() {
//function restrict scope
$('#increment').append(`<div>${count}</div>`)
count++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button id="button">Click Me!</button>
<div id="increment">
</body>
See more at this page
Upvotes: 0
Reputation: 1899
This is because of the scoping issue of count variable. Please note that JavaScript variables are accessible in scoping scenarios (block level scoping or function level scoping). More info here What's wrong with your code is you have declared the count variable in one function and you are accessing it outside of it which is not allowed. Only to fix your code, I have made the count variable as global and now it will work as expected.
Note: Please note that global variables can be accessed anywhere in the execution context, so can be used with utmost care.
$( document ).ready(function()
{
//var count =0;
});
var count=0;
$('#button').on('click', function(){
count = count + 1;
alert(count);
});
//$( "#button" ).click(function() {
// count=count+1;
// addDiv(count);
//});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='button'>Click Me</button>
Upvotes: 0
Reputation: 394
try this
var count=0;
$(document).ready(function(){
$("#add-div").click(function(){
count++;
$("body").append('<div id="'+count+'">div number '+count+'</div>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button id="add-div">add div</button>
<br>
<br>
</body>
Upvotes: 1