How to add +1 in a countable variable with each click?

5

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

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

Is it possible?

    
asked by anonymous 19.02.2014 / 23:09

3 answers

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++;
});

JSFiddle Example

    
19.02.2014 / 23:14
9

One more option, using closure. This is basically what Paulo Roberto did, but without a 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)); 
    
19.02.2014 / 23:24
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 );
} );

Update

Since the base is of the count variable, you can do something like this:

HTML

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

jQuery

var count = 5;
$('#count').click( function ( ) {
  count++;
  alert( count );
}
    
19.02.2014 / 23:17