title: How to define a global variable in JavaScript that can be accessed in all the functions
body: <p>Here's a sample form:</p>
  
  <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;title&gt;Sample form&lt;/title&gt;
  &lt;script type="text/javascript"&gt;
  function displayResult() {
  alert(document.myForm.myInput.value);
  }
  function getFocus() {
    if (document.myForm.myInput.value == document.myForm.myInput.defaultValue) {
      document.myForm.myInput.value = "";
    }
  }
  function loseFocus() {
    if (document.myForm.myInput.value == "") {
      document.myForm.myInput.value = document.myForm.myInput.defaultValue;
    }
  }
  &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;form name="myForm" method="get" onsubmit="return false;" action=""&gt;
          &lt;input name="myInput" value="Hello world!" onfocus="getFocus();" onblur="loseFocus();"&gt;&lt;br&gt;
          &lt;input type="button" onclick="displayResult();" value="Display input value"&gt;
      &lt;/form&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>It works with no problem, but the following doesn't although the variable <em>x</em> seems right:</p>
  
  <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;title&gt;Sample form&lt;/title&gt;
  &lt;script type="text/javascript"&gt;
  var x = document.myForm.myInput;
  function displayResult() {
  alert(x.value);
  }
  function getFocus() {
    if (x.value == x.defaultValue) {
      x.value = "";
    }
  }
  function loseFocus() {
    if (x.value == "") {
      x.value = x.defaultValue;
    }
  }
  &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;form name="myForm" method="get" onsubmit="return false;" action=""&gt;
          &lt;input name="myInput" value="Hello world!" onfocus="getFocus();" onblur="loseFocus();"&gt;&lt;br&gt;
          &lt;input type="button" onclick="displayResult();" value="Display input value"&gt;
      &lt;/form&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>What's wrong with it and how can I define a global variable to be used by all the functions?</p>