Reputation: 79
I'm very new to javascript, and I'm trying to create a simple real-time calculation.
The idea is that I start with 0 and can use either button to add or subtract, and that the result will be displayed in my 'demo' div.
I'm trying to 'select' that result with var y = document.getElementById("demo").value; but clearly it doesnt work...
I know this might be very inefficient code but I'm still learning
HTML
<div>Score: <div id="demo">0</div> total points</div>
<button onclick="first()" href="#number-1">this adds 10</button>
<button onclick="second()" href="#number-1">this adds 7</button>
<button onclick="third()" href="#number-2">this subtracts 5</button>
<button onclick="reset()" href="#number-2">reset</button>
Javascript
function first() {
var y = 0;
var z = 10;
var x = +y + +z;
document.getElementById("demo").innerHTML = x;
}
function second() {
var y = document.getElementById("demo").value;
var z = 7;
var x = +y + +z;
document.getElementById("demo").innerHTML = x;
}
function third() {
var y = document.getElementById("demo").value;
var z = -5;
var x = +y + +z;
document.getElementById("demo").innerHTML = x;
}
function reset() {
var y = 0;
var z = -0;
var x = +y + +z;
document.getElementById("demo").innerHTML = x;
}
http://codepen.io/anon/pen/BLxoZy
Upvotes: 0
Views: 1195
Reputation: 1231
It's not working because of document.getElementById("demo").value
, you need to use document.getElementById("demo").innerHTML
for collecting value like this -
function first() {
var y = 0;
var z = 10;
var x = +y + +z;
document.getElementById("demo").innerHTML = x;
}
function second() {
var y = document.getElementById("demo").innerHTML;
var z = 7;
var x = +y + +z;
document.getElementById("demo").innerHTML = x;
}
function third() {
var y = document.getElementById("demo").innerHTML;
var z = -5;
var x = +y + +z;
document.getElementById("demo").innerHTML = x;
}
function reset() {
var y = 0;
var z = -0;
var x = +y + +z;
document.getElementById("demo").innerHTML = x;
}
Using document.getElementById("demo").value
, you can collect form input value & using document.getElementById("demo").innerHTML
, you can collect data from your HTML tag.
Upvotes: 0