/    Sign up×
Community /Pin to ProfileBookmark

why won’t this simple code work?

?I’m learning Javascript. Does anyone know why this code returns an error message ‘form’ is undefined. But the button works fine. What’s the difference between using a button or an <a href> link? I googled this and could not produce answers.

[CODE]<html>
<head>
<title>memory test</title>
<script language = “javascript”>
function MsgBox(greeting) {
alert(greeting);
}
</script>
</head>
<body>
this is the form.
<form>
<input name=”text1″ type=”text” />
<input type=”button” value=”show text” onClick=”MsgBox(form.text1.value)” />
<br />
<a href=”javascript:MsgBox(form.text1.value)”>submit</a>
</form>
</body>
</html>[/CODE]

Thank you.

-ac

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@ZeroKilledOct 10.2008 — on html, difference are very clear, a link connect you to another document and a button do nothing by itself, except a submit type. on javascript, there is also some differences, both element doesn't contain same object and properties. however, form's element inherit the object [b]form[/b] which is a reference to the form that contain them. that is the reason [b]form[/b] is undefined on the link, it don't matter if the link is contained within a form element. if you want the link to work as your button do, you have to reference the field in any of the available ways: giving the field an ID, using the hierarchy of the document, or using the node model.
Copy linkTweet thisAlerts:
@aj_nscOct 11.2008 — I think what ZeroKilled meant to say was use:

onClick="MsgBox(document.form.text1.value)"
×

Success!

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