Reputation: 102
How to change an variable inside a function? I trying to archive an simply toggle function based on one preassigned value. Here the code and here http://jsfiddle.net/StartStep/jLQyx/
<p onclick="testit()">CLick</p>
<p id="value">Value</p>
var valuediv = document.getElementById("value");
function testit() {
if (c == 1) {
var c = 1;
valuediv.innerHTML = c
} else {
var c = 0;
valuediv.innerHTML = c
}
}
Upvotes: 0
Views: 73
Reputation: 361
Have a look at how JavaScript uses Global Variables here.
var valuediv = document.getElementById("value");
var c = 1;
function testit() {
if(c === 1)
{
c = 0;
valuediv.innerHTML = c
} else {
c = 1;
valuediv.innerHTML = c
}
}
This fixes your code. You were creating new "c" variables in your if/else blocks due to prefixing them with "var".
Fiddle: http://jsfiddle.net/jLQyx/2/
Upvotes: 3
Reputation: 287990
No need to use conditionals:
var valuediv = document.getElementById("value"),
c = 1;
function testit() {
c = +!c;
valuediv.innerHTML = c
}
Upvotes: 1
Reputation: 15112
Remove var
keyword and write c = 1
& c = 0
. You're re-creating variable c
inside the function instead of updating the global c
variable.
var valuediv = document.getElementById("value");
var c = 1;
function testit() {
if (c == 1) {
c = 0;
valuediv.innerHTML = c;
} else {
c = 1;
valuediv.innerHTML = c;
}
}
Upvotes: 1