38

I'm making a system where a user clicks a button and their score increases. There is a counter which I would like to increase the value of using jQuery (so that the page does not need to refresh) when the button is clicked.

How would I go about this?

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">

$("#update").click(function() {
$("#counter")++;
}

</script>

#update is the button, #counter is the counter.

In php, ++ increases something's value. What's the jQuery equivalent?

Also, when the button is clicked, it needs to send a request which updates the score value in a mysql database as well, without the page refreshing. Does anyone know how I would do that?

Thanks a lot

UPDATE:

I've tried a few of the methods below, but nothing seems to work! Do I need to change anything else for it to work? I've created a test page for it:

<html>
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">

var count = 0;

$("#update").click(function() {
    count++;
    $("#counter").html("My current count is: "+count);
}

</script>
<button id="update" type="button">Button</button>
<div id="counter">1</div>
</body>
</htlm>
Taimur
  • 3,171
  • 8
  • 32
  • 38
  • *#counter is the counter*: Is it an element containing a number or what? – Felix Kling Jan 15 '11 at 18:39
  • yeah, #counter is a div with a number inside – Taimur Jan 15 '11 at 18:47
  • @Taimur your code is not valid. End your click function with `});` and not just `}`. **DEMO:** http://jsfiddle.net/marcuswhybrow/Bwdfw/ – Marcus Whybrow Jan 15 '11 at 18:55
  • I tried that, and I also tried literally copying and pasting your second demo thing, but it is not working :( If it helps, I'm using WAMP server and the test page is a .php page, but I'm pretty sure that doesn't matter – Taimur Jan 15 '11 at 18:59
  • Don't know if you solved your problem, but you have to wrap your code in to the document ready handler. Currently jQuery does not find the element with ID `#button` because it is not parsed yet. Put your code into `$(function(){ your code here });`. (and the already mentioned missing `);` at the end of your click handler passing. What you have is `$(..).click(...` but you need `$(...).click(...);`). – Felix Kling Jan 15 '11 at 19:09
  • it's because you're trying to execute your code without waiting for the DOM to be ready for jQuery: look at my edited answer below: – jpea Jan 15 '11 at 19:27

7 Answers7

63

You cannot use ++ on something which is not a variable, this would be the closest you can get:

$('#counter').html(function(i, val) { return +val+1 });

jQuery's html() method can get and set the HTML value of an element. If passed a function it can update the HTML based upon the existing value. So in the context of your code:

$("#update").click(function() {
    $('#counter').html(function(i, val) { return +val+1 });
}

DEMO: http://jsfiddle.net/marcuswhybrow/zRX2D/2/

When it comes to synchronising your counter on the page, with the counter value in your database, never trust the client! You send either an increment or decrement signal to you server side script, rather than a continuous value such as 10, or 23.

However you could send an AJAX request to the server when you change the HTML of your counter:

$("#update").click(function() {
    $('#counter').html(function(i, val) {
        $.ajax({
            url: '/path/to/script/',
            type: 'POST',
            data: {increment: true},
            success: function() { alert('Request has returned') }
        });
        return +val+1;
    });
}
Marcus Whybrow
  • 19,578
  • 9
  • 70
  • 90
  • This works fine in the demo thing, but for some reason, it's not working on my page. In fact, none of the answers are! Is there something I'm missing? – Taimur Jan 15 '11 at 18:44
  • Thanks for the reply, regarding the AJAX thing, how does it know whether the function was a success? Also, what does (i,val) do? Thanks – Taimur Jan 15 '11 at 18:54
  • @Marcus Consider `+val + 1` instead of `val * 1 + 1` – Šime Vidas Jan 15 '11 at 18:58
  • Take a look at the [jQuery docs for AJAX](http://api.jquery.com/jQuery.ajax/) for more details. Any request that returns with HTTP 200 is "successful". jQuery's `html()` method can accept a callback which is passed two values the index of the current element in the jQuery selector `i`, and the current HTML value of that element `val`. Again see the [jQuery docs for more information](http://api.jquery.com/html/#html2). – Marcus Whybrow Jan 15 '11 at 19:00
  • @Sime is it more efficient since it is arithmetic instead of multiplication? – Marcus Whybrow Jan 15 '11 at 19:01
  • @Marcus I don't think that efficiency is an issue here. Both methods take approx. 17 picoseconds to execute `:D`. It's readability that I care about. The unary plus operator is the most readable method of casting a string into a number. – Šime Vidas Jan 15 '11 at 19:05
  • 1
    if you just copy and paste into what you have currently, almost none of it will work because you're missing jQuery's "ready" function - $(document).ready – jpea Jan 15 '11 at 21:52
21
$(document).ready(function() {
var count = 0;

  $("#update").click(function() {
    count++;
    $("#counter").html("My current count is: "+count);
  }

});

<div id="counter"></div>
jpea
  • 3,114
  • 3
  • 26
  • 26
  • you needed to add the document ready function before firing any jQuery code (edited above) – jpea Jan 15 '11 at 19:28
10

It's just

var counter = 0;

$("#update").click(function() {
   counter++;
});
Vadim
  • 17,897
  • 4
  • 38
  • 62
8

Several of the suggestions above use global variables. This is not a good solution for the problem. The count is specific to one element, and you can use jQuery's data function to bind an item of data to an element:

$('#counter').data('count', 0);
$('#update').click(function(){
    $('#counter').html(function(){
        var $this = $(this),
            count = $this.data('count') + 1;

        $this.data('count', count);
        return count;
    });
});

Note also that this uses the callback syntax of html to make the code more fluent and fast.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • Not true if there's more than one way of changing the value of count – jcuenod Jan 15 '11 at 18:34
  • @j3frea Then encapsulate the code in a plugin. Honestly, this isn't hard to do, and littering your code with global variables is very bad design. – lonesomeday Jan 15 '11 at 18:36
  • Nobody is using global variables, they are just examples. The context is not stated in any answer. – Marcus Whybrow Jan 15 '11 at 18:43
  • Don't forget to initialize the counter beforehand, otherwise it won't work: `$('#counter').data('count', 0);` – Šime Vidas Jan 15 '11 at 18:53
  • @Sime Thanks. I always want `undefined` to equal `0` in mathematical operations... @Marcus Well, some are. Constraining the context should be an integral part of the answer, in that case. – lonesomeday Jan 15 '11 at 19:00
1

Go to the below site and tryout. http://www.counter12.com/

From the above link I have selected the one design that I liked to have in my site accepted terms and it has given me a div that I have pasted in my html page.

It did awesomely worked.

I am not answering to your problem on JQuery, but giving you an alternate solution for your problem.

Anil
  • 337
  • 2
  • 10
0

I'm going to try this the following way. I've placed the count variable inside the "onfocus" function so as to keep it from becoming a global variable. The idea is to create a counter for each image in a tumblr blog.

$(document).ready(function() {

  $("#image1").onfocus(function() {

  var count;

    if (count == undefined || count == "" || count == 0) {
    var count = 0;
    }

    count++;
    $("#counter1").html("Image Views: " + count);
  }
});

Then, outside the script tags and in the desired place in the body I'll add:

<div id="counter1"></div>
Max West
  • 755
  • 7
  • 11
0

You are trying to set "++" on a jQuery element!

YOu could declare a js variable

var counter = 0;

and in jQuery code do:

$("#counter").html(counter++);
stecb
  • 14,478
  • 2
  • 50
  • 68
  • You should create a global variable? Really? – Šime Vidas Jan 15 '11 at 18:33
  • "You SHOULD" ;) not "you MUST" ..it would be better "you could".. c'mon there are several ways to do this, mine it's just a suggestion! – stecb Jan 15 '11 at 18:36
  • Yes, "you could" is the correct form here. "You should" is for recommendations. And no one should recommend creating global variables, the recommendation here is the opposite: one should try to avoid creating global variables. – Šime Vidas Jan 15 '11 at 18:42
  • You're absolutely right! "global" word is my bad ;) I apologize – stecb Jan 15 '11 at 18:44