How to add +1 in a counter variable to each click?

Asked

Viewed 22,986 times

5

Each time I click a button, I want to add +1 to a variable.

For example: I have a variable count receiving the value 5, when clicking a button I want the value 5 to change to 6 and so on, displaying in a alert().

It is possible?

  • It is interesting that you post an example of what you have already tried. So we can help you with your question in a more interesting way. jsfiddle is successful.

3 answers

9

One more option, using closure. This is basically what Paulo Roberto did, but with no global variable:

function criaCounter(init) {
    var count = init || 0;
    return function() {
        count++;
        alert(count);
    }
}
// Cria contador que começa em 5, e usa como listener do click
$('#addCount').click(criaCounter(5)); 
  • Um, cool. Cool! Thanks.

  • Interesting, but you’re increasing before you give alert() therefore the value 5 would not be alerted, only from 6 henceforth, certain?

  • 1

    @Pauloroberto Certo. You can avoid if the body of the function is alert(count++).

8


Would this be?

HTML:

<input type=button id=addCount value="Adicionar Count">

Javascript:

var count = 5;//recebendo o valor 5 que você disse
$('#addCount').click(function(){
  alert(count);
  count++;
});

Example in Jsfiddle

  • 1

    That’s right! Only that so, in the first click I want to be the own number 5, has as?

  • Sure, just change the position of where the count is incremented, see my Edit.

  • Oh yes, I get it. Now it works! Thank you!

5

I could do something like this:

HTML

<button id="count" data-valor="5">Clique Aqui!</div>

jQuery

$('#count').click( function ( ) {
  var valorVelho = this.data('valor');
  var valorNovo = valorVelho++;
  this.data('valor', valorNovo);
  alert( valorNovo );
} );

Updating

Where the basis is of the variable count, Maybe do something like this:

HTML

<button id="count">Clique Aqui!</div>

jQuery

var count = 5;
$('#count').click( function ( ) {
  count++;
  alert( count );
}
  • the solution is good, but responding to the question of OP "I want a variable count receiving the value 5", your answer would not be within the context, right?

  • 1

    Right. I didn’t take into consideration the fact that I wanted to have the variable count.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.