Reputation: 15
I'm trying to make a web app, obviously for this I would need to know how to modify variables. I'm new to JS, is there something I'm missing? The following returns NaN
var example = 30
function add() {
var example = example + 10
document.getElementById("text").innerHTML = example
}
<P id="text"></text>
<button onclick="add()">
Upvotes: 0
Views: 265
Reputation: 10071
You can't re-declared the same variable example, And you have to complete properly close the button tag and paragraph tag
You will need these changes
var example = 30
function add()
{
example = example + 10
document.getElementById("text").innerHTML = example
}
<p id="text"></p>
<button onclick="add()">submit</button>
Upvotes: 0
Reputation: 360
You have re-declared the same variable, that's why on a function-scope view, example
is NaN.
var example = 30
function add() {
example += 10;
document.getElementById("text").innerHTML = example
}
Upvotes: 0
Reputation: 15509
You are redeclaring the variable in the function - also you can abbreviate is as follows: example += 10;
which is he quvalent of saying example is the value of example plus 10.
var example = 30
function add() {
example += 10;
document.getElementById("text").innerHTML = example
}
<button onclick="add()">Click Me</button>
<p id="text"></p>
Upvotes: 0
Reputation: 3782
You shouldn't redeclare the example
variable inside the function again if you want to use the value assigned outside
var example = 30
function add() {
example = example + 10
document.getElementById("text").innerHTML = example
}
<P id="text"></p>
<button onclick="add()">Add</button>
Upvotes: 1