Quetion regarding local and global variable in javascript

Posted by caramel1991 on Stack Overflow See other posts from Stack Overflow or by caramel1991
Published on 2010-06-15T07:55:04Z Indexed on 2010/06/15 8:12 UTC
Read the original article Hit count: 175

Filed under:

Today,I started to code a page that prompt the user to choose their PC spec,and the code is as follow

<html>
<title>Computer Specification Chooser</title>

<head>

<script type="text/javascript">

var compSpec = document.compChooser;

function processorUnavailable_onclick()
{
 alert("Sorry that processor speed is currently unavailable");
 compSpec.processor[2].checked = true;

}

</script>

</head>

<body>

<form name="compChooser">

<p>Tick all components you wan included on your computer</p>

<p>
DVD-ROM

<input type="checkbox" name="chkDVD" value="DVD-ROM" />
<br />

CD-ROM
<input type="checkbox" name="chkCD" value="CD-ROM" />
<br />

Zip Drive
<input type="checkbox" name="chkZIP" value="ZIP DRIVE" />
</p>

<p>
Select the processor speed you require
<br />

<input type="radio" name="processor" value="3.8" />
3.8 GHZ

<input type="radio" name="processor" value="4.8" onclick="processorUnavailable_onclick()" />
4.8 GHZ


<input type="radio" name="processor" value="6" />
6 GHZ
</p>

<input type="button" name="btnCheck" value="Check Form" />

</form>

</body>
</html>

The problem I'm facing is on the function that I've tie to the event handler,when I try to choose the radio button of the processor value 4.8 GHZ,yes it alert me with the message inside the function,but after that,it doest not execute the next statement inside the function,that is to check the next processor value 6 GHZ,I've try my effort to change it and test on it,and find out when I set the var compSpec = document.compChooser as a local variable inside the function instead of a global variable,the next statement could be executed.But I thought for a global variable,it is accessible in everywhere on the page and also inside a function.But why now I can't accesses it inside my function??Any idea??Besides,I stumble upon a weird article while googling,it says that when a global variable is created,it is added to window object.I just curious why this happen??And what's the benefits and uses of it??THANK YOU

© Stack Overflow or respective owner

Related posts about JavaScript