pasha_codes
pasha_codes

Reputation: 635

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>

Upvotes: 7

Views: 38828

Answers (5)

Misterwyz
Misterwyz

Reputation: 101

The best option will be to pass in an event object from the rps() method in the HtML,       like this: rps(event).
Then retrieve it from the Javascript method like this:
function rps(event) {
var computerScore = event.CurrentTarget.innerText;
computerScore++;
computerScore = number;
}

Upvotes: 0

vsync
vsync

Reputation: 130670

var elm = whatever //assuming you select your element using the DOM
// update value
elm.innerHTML = +elm.innerHTML + 1;

Upvotes: -3

Explosion Pills
Explosion Pills

Reputation: 191809

A couple issues:

  1. computerScore is nothing; you probably want document.getElementById('computerScore')
  2. value on a <p> is not valid. Use data-value or something instead (or

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

Note that dataset.value is a string, but the ++ coerces it to an integer.

http://jsfiddle.net/vqPKZ/

I would also suggest using event bindings rather than event attributes, e.g. button.addEventLister

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382464

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

Upvotes: 1

Adam Plocher
Adam Plocher

Reputation: 14243

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>

Upvotes: 15

Related Questions