/    Sign up×
Community /Pin to ProfileBookmark

How to define a global variable for all the functions

Hi,

Here’s a sample form:

[CODE]<!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>[/CODE]

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

[CODE]<!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>[/CODE]

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

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@007JulienJan 17.2012 — The document does not exist at the beginning of the script. Then x is not define ! With an argument for the two functions onfocus and loseFocus, you could define x in this functions.
×

Success!

Help @Rain_Lover spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...