/    Sign up×
Community /Pin to ProfileBookmark

help with global variable

why does this only work if the [COLOR=Red]var a=document.form1.myselect[/COLOR]; is defined in the function ? if its defined before the function it does not work, even though i’ve made it global.

<html xmlns=”http://www.w3.org/1999/xhtml“>
<head><script type=”text/javascript”>
[COLOR=Red]var a=document.form1.myselect;[/COLOR]
function myfunc(){
[COLOR=Red]// THIS WORKS — var a=document.form1.myselect;[/COLOR]
alert(a.options[a.selectedIndex].value);
}

</script>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>Untitled Document</title>
</head>

<body>
<form id=”form1″ name=”form1″ method=”post” action=””>
<label>
<select name=”myselect” id=”myselect”>
<option value=”oneone”>one</option>
<option value=”twotwo”>two</option>
<option value=”threethree”>three</option>
</select>
</label>
<p>&nbsp;</p>
<p><input type=”button” value=”click me” onclick=”myfunc()” />&nbsp;</p>
</form>
</body>
</html>

Thank you

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@FangSep 26.2006 — Because it's global it's parsed before the element exists.
Copy linkTweet thisAlerts:
@KorSep 26.2006 — do you really nead your page to be an XHTML page? In this case, you should follow the XHTML rules to write tags, which is a tough job...
Copy linkTweet thisAlerts:
@ev66authorSep 26.2006 — thanks

what should i use ? do you mean this

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
Copy linkTweet thisAlerts:
@KorSep 27.2006 — yeap... or strict (but for strict doctype you should use CSS for most of the attributes (amongs other strict rules).
Copy linkTweet thisAlerts:
@ev66authorSep 27.2006 — ok. Thanks for quick response Kor.
×

Success!

Help @ev66 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,
)...