In this lesson, you will learn how to read input from a form and handle its submission using JavaScript.
Imagine you want to sign up for a newsletter. You fill in your email address on a webpage and click “Subscribe.” That action submits your email to the site. We will create a similar form and learn how to capture the input when it is submitted.
File: form-example.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Submission Example</title>
</head>
<body>
<form id="myForm">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>
<p id="output"></p>
<script>
const form = document.getElementById('myForm');
form.addEventListener('submit', function(event) {
event.preventDefault();
const email = document.getElementById('email').value;
document.getElementById('output').textContent = `Submitted email: ${email}`;
});
</script>
</body>
</html>
Submitted email: example@example.com
The line const form = document.getElementById('myForm'); selects the form element. The following line adds an event listener for the submit event. This means it will execute the function when the form is submitted. The method event.preventDefault(); stops the form from refreshing the page. Finally, it reads the input value and displays it on the page.
Now it’s your turn! Modify the form to include a text input for a name. When submitted, display both the name and email below the form.
File: form-example-solution.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Submission Example</title>
</head>
<body>
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>
<p id="output"></p>
<script>
const form = document.getElementById('myForm');
form.addEventListener('submit', function(event) {
event.preventDefault();
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
document.getElementById('output').textContent = `Submitted name: ${name}, email: ${email}`;
});
</script>
</body>
</html>
event.preventDefault();, the form will reload the page instead of showing your output. Remember to include it.getElementById('wrongId'), it will return null. Ensure your IDs in the HTML match your JavaScript.