Today, I started to code a page that prompts the user to choose their PC specification, and the code is as follows.
<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 want included in 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 in the function that I've tied to the event handler. When I try to choose the radio button of the processor value 4.8 GHz, yes it alerts me with the message inside the function, but after that, it doesn’t not execute the next statement inside the function, that is, to check the next processor value, 6 GHz.
I've tried to change it and test on it, and found 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 everywhere on the page and also inside a function. But why now can't I accesses it inside my function?
Besides, I stumbled upon a weird article while googling. It says that when a global variable is created, it is added to the window
object. Why does this happen? And what are the benefits and uses of it?