How to add value to the variable in jQuery?

3
  • I have a variable x that is written on the screen with initial value 0;
  • I want each click of a button (be input or button same) in the HTML file, the value of that variable to be added 1;
  • When added, I want the variable, which is written on the screen, to show the current value of the variable.

I tried the following:

var pontos = 0;

$(document).ready(function() {
    $('#pontos').text('Olá! O seu recorde é de ' + pontos + ' pontos.');

    $('#addPonto').click(function() {
        pontos++;
    });
});

When you do this, I want the value written on the screen to be updated. How to proceed?

    
asked by anonymous 09.05.2015 / 03:18

2 answers

4

Your code is right, just the step where you write on the page, or change the text that is in #pontos again using the line you already have but within the function that is run with each click. >

You can also put this #pontos element in cache so you do not have to go fetch with jQuery with each click. I leave a suggestion, which uses less jQuery:

var pontos = 0;
$(document).ready(function () {
    var divPontos = document.getElementById('pontos');
    divPontos.innerHTML = 'Olá! O seu recorde é de ' + pontos + ' pontos.'
    $('#addPonto').click(function () {
        pontos++;
        divPontos.innerHTML = 'Olá! O seu recorde é de ' + pontos + ' pontos.'
    });
});

example: link

    
09.05.2015 / 07:45
2

In case, to update the value, you would have to rewrite the field update, within the button click action, like this:

var pontos = 0;
$(document).ready(function() {
    $('#pontos').text('Olá! O seu recorde é de ' + pontos + ' pontos.');

     $('#addPonto').click(function() {
            pontos++;
            $('#pontos').html('Olá! O seu recorde é de ' + pontos + ' pontos.');
    });
});

In this way the field modification is linked to the button click.

    
09.05.2015 / 04:37