0

I am accessing javascript variable but i am not able to access it using the following code.

<script type="text/javascript">
function msg1(a)
{
        var1=a;

}

function msg2(b)
{
        var2=b; 

}
</script>

<input type="radio" name="people" onfocus="msg1(this.value);" value="2">
<input type="radio" name="rating" onfocus="msg2(this.value);" value="5">

<script type="text/javascript"> 
        if(var1==2 && var2==5)
        document.getElementById("scores").innerHTML='511';  
</script>

However instead of calling the function through onfocus event, when I call the function directly,the code runs.The code that is working is:-

<script type="text/javascript">
    function msg1(a)
    {
            var1=a;

    }

    function msg2(b)
    {
            var2=b; 

    }
    msg1(2);
    msg2(5);
            if(var1==2 && var2==5)
            document.getElementById("scores").innerHTML='511';  
    </script>

I can't figure out what is the error in the code that is not working. Plz suggest me.

  • A tiny bit related: [What is the scope of variables in JavaScript?](http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript), you're setting globals, which can be a little risky. – Cerbrus Jun 17 '15 at 14:06
  • @Cerbrus — No, this has nothing to do with scope. – Quentin Jun 17 '15 at 14:07
  • @Quentin: Ah, you're right. Completely overlooked the `onfocus`. At least I didn't mjolnir. – Cerbrus Jun 17 '15 at 14:08
  • I think a simple `var1 = 0, var2 = 0;` before `function msg1(a)` will make it work. @Quentin has given the explanation for the same. – Obscure Geek Jun 17 '15 at 14:12
  • @ObscureGeek — No, that will stop it from erroring. It won't make it work because the IF THEN innerHTML code won't be rerun when the values change. – Quentin Jun 17 '15 at 14:13
  • @Quentin I see your point. I think the error will go but the desired working will not be achieved. An event handler or a wrapper function for the check seems the correct way to go. – Obscure Geek Jun 17 '15 at 14:16

1 Answers1

2

This is a timing problem.

  • You try to read the variables when the page loads.
  • You try to set the variables when the inputs receive focus.

Since they haven't been set at the time you try to read them, you get an error.

You never try to read them again.

You have to set them before you can read them.


Move the logic for testing the values of the variables inside the event handlers that change them.

You should also declare them (and possibly give them default values) when you load the page. Otherwise the first event handler will try to set one of them and then read both of them (at which point one will be undeclared and you'll still get a reference error).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335