/    Sign up×
Community /Pin to ProfileBookmark

HTML using javascript closure

I was wondering how I might make a simple HTML that uses closure to make my variables non-global.

I have this code (that does not work) below. I hope it gets across what I am trying to do. I am new to JavaScript (one month now). Any suggestions?

[code]
<html>
<body>

<h1>Closure Test 1</h1>
<form name=”myform”>
<table border=”0″ cellspacing=”0″ cellpadding=”5″><tr>
<td><textarea name=”inputtext” rows=’23’ cols=’80’ onBlur=”addtext();”></textarea></td>
</tr></table>
</form>
<script type=”text/javascript”>
(function() {
function addtext() {
var newtext = document.myform.inputtext.value;
document.myform.outputtext.value = “”;
}
})();
</script>
</body>
</html>
[/code]

to post a comment
HTML

1 Comments(s)

Copy linkTweet thisAlerts:
@brightmatterauthorDec 22.2009 — This is what I was trying to do but the variable is still global! What gives?&lt;html&gt;
&lt;body&gt;
&lt;h1&gt;
Closure Test 1
&lt;/h1&gt;
&lt;form name="myform"&gt;
&lt;table border="0" cellspacing="0" cellpadding="5"&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;textarea name="closure_txt_area" rows="23" cols="80" onBlur="closure();" onFocus="notClosure();"&gt;&lt;/textarea&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/form&gt;
&lt;script type="text/javascript"&gt;
function closure() {
(function() {
newtext = document.myform.closure_txt_area.value;//makes implied global
document.myform.closure_txt_area.value = "Inside Closure: "" + newtext + """;//proves variable is set
})();
}
function notClosure() {
if(newtext) {
document.myform.closure_txt_area.value = "Global";//proves variable is global
} else {
document.myform.closure_txt_area.value = "Local";//proves variable is local
}
}
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
×

Success!

Help @brightmatter 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.15,
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: @nearjob,
tipped: article
amount: 1000 SATS,

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

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