0

Ok I am definitely puzzled, why this is not returning 6 in textarea. It doesn't return anything. I figured that it has something to do with js scopes, but i cant figure it out.

<body>

    <script language="Javascript">
    var broj = 5;  

    function Inci(){
    var broj++;
    document.frmMain.VrsteHolder.value = broj;
    }

    </script>

    <form name="frmMain" method="get" action="script.php">

    <textarea name="VrsteHolder" rows="4"> </textarea>
    <input type="button" value="Dodaj porudzbinu" name="buttonDodaj" onClick="Inci();"/> 

    </form>

</body>
1

3 Answers 3

3

Get rid of the var keyword inside of the Inci function.

var redeclares variables in the current scope, so it will redeclare broj every invocation of Inci.

This would be the correct way:

var broj = 5;  

function Inci(){
   document.frmMain.VrsteHolder.value = ++broj;
}
Sign up to request clarification or add additional context in comments.

3 Comments

+1 usually one uses the var inside a function for the sake of leaving the outside variables untouched (ex. you have var hey outside and need to use the same name in the function without editing the global one)
ok i did that, but now result in textarea is NaN. Not number 6 as i expected.
I figure that is right solution, but for me it keep returning NaN. I will try to rework rest of code, thx anyway.
0

because the var keyword defines the variable. Remove var from your function:

function Inci(){
    broj++;
    document.frmMain.VrsteHolder.value = broj;
    }

1 Comment

ok i did that, but now result in textarea is NaN. Not number 6 as i expected.
0

The problem is var as the other answers detail, redeclaring your variable, or attempting to rather, and actually throwing a syntax error because of the combination.

As an aside though that I'm seeing less: don't forget you can increment and get the result immediately by having the ++ (increment operator) before the variable, for example:

function Inci(){
  document.frmMain.VrsteHolder.value = ++broj;
}

You can test that version out here.

1 Comment

ok i did that, but now result in textarea is NaN. Not number 6 as i expected.

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.