Question :
- I have a variable
x
that is written on the screen with initial value 0; - I want each click of a button (be
input
orbutton
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?
Answer :
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
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.