Reputation: 111
I want a counter that increases on button click. I tried the following code, but the value printed stays the same:
$(document).ready(function () {
$("#gonder").click(function() {
var baslik = document.title;
var sayi = 1;
var sayi1 = sayi++;
document.title = '(' +sayi+ ')' + baslik;
});
});
What how can I do my want?
Upvotes: 2
Views: 10682
Reputation: 1
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id="btn" onclick="f1();">Button</button>
<p id="demo"></p>
<script>
var count=0;
function f1()
{
document.getElementById("demo").innerHTML=count;
count++;
}
</script>
</body>
</html>
Upvotes: 0
Reputation: 2226
You might try:
<button class="counter">I have been clicked 0 times</button>
<script type="text/javascript">
var count = 0;
$('button.counter').click(function(){
count++;
$(this).text("clicked "+count+" times");
});
</script>
That is the simplest I can think of.
Upvotes: 0
Reputation: 30135
I think this is what you want:
var sayi = 1;
var baslik = document.title;
$("#gonder").click(function() {
document.title = '(' + (++sayi) + ')' + baslik;
});
Upvotes: 0
Reputation: 4861
var clickCounter = 0;
$(document).ready(function () {
$("#gonder").click(function() {
var baslik = document.title;
var sayi = 1;
clickCounter++;
document.title = '(' +sayi+ ')' + baslik;
});
});
Upvotes: 0
Reputation: 76870
The simplest i can think of
<button>clicked 0 times</button>
var count = 0;
$('button').click(function(){
count++;
$(this).text("clicked "+count+" times");
});
fiddle here http://jsfiddle.net/PKcrd/
Upvotes: 4
Reputation: 114347
You need to initialize your counter outside of the function. You were clearing it on every click.
var sayi = 1;
$(document).ready(function () {
$("#gonder").click(function() {
var baslik = document.title;
sayi++;
document.title = '(' +sayi+ ')' + baslik;
});
});
Upvotes: 1
Reputation: 62392
Here is a fairly detailed writup I did on closures using your exact goal as the straw man (er... problem)
http://jondavidjohn.com/blog/2011/09/javascript-event-handler-persistance-with-closures
Basically you can do it one of 2 ways.
create a counter variable outside the scope of the event handler.
var count = 0;
element.onclick = function() {
count++;
};
use a closure to provide each element its own unique counter contained within the event handler itself. Which I detail in my blog post.
Upvotes: 2