/    Sign up×
Community /Pin to ProfileBookmark

If one click on “set” and then on “verify”, the global variable “variablename” should not be “undefined”. Works with any browser, but not with IE6. Is this a bug?

<html><head><title>test</title></head>
<body>
<form>
<input type=”button” value=”set” onclick=”variablename = ‘abc’;”>
<a href=”javascript:alert(typeof(variablename));”>verify</a>
</form>
</body></html>

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@phpnoviceJun 10.2006 — Maybe -- maybe not. It appears to at least be a difference in how the browser interprets "scope". In all browsers, a form has its own scope -- separate from both the document scope and the window scope. However, IE apparently treats the form scope more strictly than other browsers, in that, variables declared without the [b]var[/b] operator (but within the form scope) are considered local variables -- not global. You can work around this by calling a function in the HEAD from your in-line form button event -- rather than setting the variable directly in the in-line form button event handler. You can also work around this problem by explicitly setting the variable as a property of the [B]window[/B] object -- where all true global variables are defined.

I set up the following test example which all result in the creation of a true global variable:
[code=html]<html>
<head>
<title>test</title>
<script>
function setvar() {
variablename = 'abc';
return true;
}
</script>
</head>

<body>
<form><p><input type="button" value="set in form scope" onclick="window.variablename='abc'"></p>
<p><input type="button" value="set in window scope" onclick="setvar()"></p></form>
<p><button onclick="variablename = 'abc'">set in document scope</button></p>
<p><button onclick="alert(typeof(variablename))">verify in window scope</button></p>
</body>
</html>[/code]
×

Success!

Help @nvx 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 6.2,
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: @meenaratha,
tipped: article
amount: 1000 SATS,

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

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...