How to add value to variable in jQuery?

Asked

Viewed 8,493 times

3

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

I tried it this way:

var pontos = 0;

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

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

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

2 answers

4


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

You can also put this element #pontos cached so you don’t have to search with jQuery every click. I leave a hint, 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: http://jsfiddle.net/jw087L4u/

  • 1

    Thank you very much, Sergio. I was a while without internet access, so the delay.

2

In this case, to update the value, Voce would have to rewrite the field update, within the action of clicking the button, this way:

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.');
    });
});

This way the field modification is connected to the button click.

  • Thank you very much!

  • @Gabrielazevedo remembering that it is always good to mark the question as answered if the answer solved your problem...

Browser other questions tagged

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