Reputation: 635
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
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
Reputation: 130670
var elm = whatever //assuming you select your element using the DOM
// update value
elm.innerHTML = +elm.innerHTML + 1;
Upvotes: -3
Reputation: 191809
A couple issues:
computerScore
is nothing; you probably want document.getElementById('computerScore')
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.
I would also suggest using event bindings rather than event attributes, e.g. button.addEventLister
Upvotes: 0
Reputation: 382464
A few problems :
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
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