Local and global variables in javascript -


Today, I started to start a page code that encouraged users to select their PC specs, And the code is followed

   & Lt; Br / & gt; CD-ROM & lt; Input type = "checkbox" name = "chkCD" value = "CD-ROM" /> & Lt; Br / & gt; Zip drive & lt; Input type = "checkbox" name = "chkZIP" value = "zip drive" /> & Lt; / P & gt; & Lt; P & gt; Select the processor speed you need & lt; Br / & gt; & Lt; Input type = "radio" name = "processor" value = "3.8" /> 3.8 GHz & Lt; Input type = "radio" name = "processor" value = "4.8" onclic = "click the processor unavailable_online" /> 4.8 GHz & amp; Lt; Input type = "radio" name = "processor" value = "6" /> 6 GHZ & lt; / P & gt; & Lt; Input type = "button" name = "btn check" value = "check form" /> & Lt; / Form & gt; & Lt; / Body & gt; & Lt; / Html & gt;  

The problem facing the function is that I have tie the event handler, when I try to select the radio button of the processor value 4.8 GHz, Warns the message inside the function, but after that, it does not execute the next statement inside the function, which is to check the next processor value 6 GHz.

I have tried to try to change it and test it on it, and when I have a local variable inside the function instead of var compSpec = document.compChooser < / Code>, the next statement can be executed.

But I thought of a global variable, it can be accessed anywhere on the page and within a function.But why can not I enter it in my ceremony now? Any ideas ??

In addition to this, I mess up on a strange article while goggling, it says that when a global variable is created, it is added to the window object. I am just curious that such a Why is that? And what are its benefits and uses ??

In Javascript, a global variable is the property of the global object. When running inside the browser, the global object is the window object so if you do not use the keyword var , you are not actually declaring a variable, instead you Setting the property of the window is useful because the window object is accessible from everywhere, and this is also your global variable.

If you set your processorUnavailable_onclick function inside a variable ( var ) to compSpec , its scope (and its function) Built-in closure). If you set compSpec as a global variable (i.e., a property of window ), then it will be available from everywhere:

  function body_onload () {Window.compSpec = document.compChooser; } Function processor available_on click () {warning ("sorry that the processor speed is currently unavailable"); Window.compSpec.processor [2]. Checked = true; } ... & lt; Body onload = "body_onload ()" & gt; ...  

Comments

Popular posts from this blog

windows - Heroku throws SQLITE3 Read only exception -

lex - Building a lexical Analyzer in Java -

python - rename keys in a dictionary -