Step 1 is to use HTML 5, indent your code, and use semicolons.
<!DOCTYPE html>
<html>
<head>
<title> Page 1 </title>
<script>
function myFunction() {
var x = document.getElementById("myEmail");
document.write(x);
}
</script>
</head>
<body>
<form>
<p> Input your email </p>
<input name="myEmail" type="text">
</form>
<button type="button" onclick="myFunction()">Submit Email</button>
</body>
</html>
Step 2 is to look at what’s being written, see that it’s null
, intuit when document.getElementById
would return null
, and realize that there is no element with an id
of myEmail
in your document. It just has a name
. Drop the form while you’re at it.
<body>
<p>Input your email </p>
<input id="myEmail" type="text">
<button type="button" onclick="myFunction()">Submit Email</button>
</body>
The next step is to try that again and realize that x
is an element, not a string, and you want to get its value.
function myFunction() {
var x = document.getElementById("myEmail");
document.write(x.value);
}
The “good future practice” steps are, in no particular order:
- Put your script at the bottom and stop using inline event listeners
- Put your script in an external file
- Use a
<label>
If you’re not going to do something more useful than write the e-mail back, consider also using document.body.appendChild(document.createTextNode(…))
, which will not obliterate the rest of the document. The DOM is really great.