<!DOCTYPE html>
<html>
<head>
<title>Greet</title>
</head>
<body>
<form id="demo">
<input id="name" placeholder="Name" type="text"/>
<input type="submit"/>
</form>
<script>
function greet()
{
alert('hello, ' + document.getElementById('name').value);
}
document.getElementById('demo').onsubmit = greet();
</script>
</body>
The alert does not show the name I submitted. Only hello,
. But if I rewrite code like this document.getElementById('demo').onsubmit = greet;
then it works. But why?
And this works as well:
<!DOCTYPE html>
<html>
<head>
<title>dom0</title>
</head>
<body>
<form id="demo" onsubmit="greet()">
<input id="name" placeholder="Name" type="text"/>
<input type="submit"/>
</form>
<script>
function greet()
{
alert('hello, ' + document.getElementById('name').value);
}
</script>
</body>