0

Here is what I want to do but with another um... technique/method. The first one is working, the second is not:

<script>
function hello(){
    var number = document.getElementById("omg").innerHTML;
    if(number==undefined){
    number=0;
    }
    number++;
    document.getElementById("omg").innerHTML=number;
}

</script>


<input type="submit" value="yeah" onclick="hello()">
<div id="omg"></div>

Here is the way that I want to do it, the technique that I want to use but its not working.

<script>
function hello(){
    var number;
    if(number==undefined){
    number=1;
    }
    document.getElementById("omg").innerHTML=number;
    number++;
}

<input type="submit" value="yeah" onclick="hello()">
<div id="omg"></div>

Instead of taking the last value from the div I want to like take it from a string in the function. So the point is that each time I click the button the number increases by one.

0

2 Answers 2

1

ok, you'll need to make number a global variable, not a local variable to your function. Otherwise every time you call that function, it'll reset number to 1.

var number;

function hello(){ 
    if(number==undefined){
      number=1;
    }
    document.getElementById("omg").innerHTML=number;
    number++;
}
Sign up to request clarification or add additional context in comments.

1 Comment

YEAH!, it works! thank you!, I have no idea why I didn’t try it
1

store the initial value in the div itself (saves a declaration, and you have to display something anyway)

<input type="submit" value="yeah" onclick="hello();"/>
<div id="omg">0</div>

and call the function like:

function hello(){
   var t = document.getElementById("omg").innerHTML;
   document.getElementById("omg").innerHTML = parseInt(t,10) + 1;
}

fiddle with it here

Comments

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.