How to define a global variable for all the functions

Hi,

Here’s a sample form:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Sample form</title>
<script type="text/javascript">
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;
  }
}
</script>
</head>
<body>
<form name="myForm" method="get" onsubmit="return false;" action="">
<input name="myInput" value="Hello world!" onfocus="getFocus();" onblur="loseFocus();"><br>
<input type="button" onclick="displayResult();" value="Display input value">
</form>
</body>
</html>

It works with no problem, but the following doesn’t:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Sample form</title>
<script type="text/javascript">
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;
  }
}
</script>
</head>
<body>
<form name="myForm" method="get" onsubmit="return false;" action="">
<input name="myInput" value="Hello world!" onfocus="getFocus();" onblur="loseFocus();"><br>
<input type="button" onclick="displayResult();" value="Display input value">
</form>
</body>
</html>

What’s wrong with it and how can I define a global variable to be used by all the functions?

Many thanks in advance!
Mike

The problem with the second version is that you attempt to get an object for (i.e. select) the input element BEFORE that element has been created. The solution is to put the code in a window.onload handler, which is called after all elements have been created:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Sample form</title>
<script type="text/javascript">

var x;

window.onload = function ()
   {
   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;
      }
   }
</script>
</head>
<body>
<form name="myForm" method="get" onsubmit="return false;" action="">
<input name="myInput" value="Hello world!" onfocus="getFocus();" onblur="loseFocus();"><br>
<input type="button" onclick="displayResult();" value="Display input value">
</form>
</body>
</html>

Thanks for the explanation! :slight_smile: