Reputation: 11
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.
Upvotes: 0
Views: 27
Reputation: 944426
This is a timing problem.
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).
Upvotes: 2