Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I increment a value inside HTML?

I'm completely new to JavaScript. I'm trying to increment a variable inside the HTML, it's not working. Is my syntax wrong?

<script>
function rps() {
computerScore.value++;
computerScore.innerHTML = computerScore.value;
}
 </script>   
<html>
<b>computer score:</b><p id="computerScore" value="0">-</p>
<button type="button" onclick="rps()">Go</button><br>
</html>
like image 558
pasha_codes Avatar asked Mar 07 '13 20:03

pasha_codes


2 Answers

value is not a valid attribute for the <p> tag.

I think you want something like:

function rps() {
    var computerScore = document.getElementById('computerScore');
    var number = computerScore.innerHTML;
    number++;
    computerScore.innerHTML = number;
}

...

<b>computer score:</b><p id="computerScore">0</p>
like image 185
Adam Plocher Avatar answered Oct 18 '22 01:10

Adam Plocher


A few problems :

  • on most browsers, you can't get an element by id just as a global property
  • an attribute isn't always a property of an element (the value is only a property of input elements)

You can do this :

function rps() {
   // fetch the element :
   var element = document.getElementById('computerScore'); 

   // get the attribute, parse it and increment it :
   value = parseInt(element.getAttribute('value'), 10)+1; 

   // stores the incremented value :
   element.setAttribute('value', value);

   // and change the innerHTML (conversion to string is implicit)
   element.innerHTML = value;
}
like image 26
Denys Séguret Avatar answered Oct 17 '22 23:10

Denys Séguret