0

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
    }
}
1
  • 2
    if c == 1 why are you then assigning c = 1? Commented Apr 16, 2014 at 19:35

3 Answers 3

3

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Uh, ok ahahah sorry for my dumbiness also thanks to all the other replies
Gotta start somewhere :)
1

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

http://jsfiddle.net/jLQyx/1/

Comments

1

No need to use conditionals:

var valuediv = document.getElementById("value"),
    c = 1;
function testit() {
    c = +!c;
    valuediv.innerHTML = c
}

Demo

3 Comments

Nice thing but i must use itto compare that value and execute other code with if/else... no just print the value :D Thanks to you too
@AgeLonglife OK, but try to place identical statements in if and else outside the conditional, if possible.
but if I use "case/if" it would be something different

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.