Exercise 3: Form Handling with Validation
Create a form that accepts name, age, and email address. The form should include validation and require for each field. Upon form submission, it should display “Name, age” on the page with the email address being used as a mailto hyperlink on the name.
Using the example code below,
- Add email and age fields
- Declare the necessary variables
- Have the username link to the email followed by a comma with the age.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Forms and Variables</title>
<style>
label,
input {
display: block;
margin-bottom: 0.5em;
}
</style>
</head>
<body>
<h1>Forms and Variables</h1>
<form name="myForm">
<label for="name">Name:</label>
<input id="name" type="text" placeholder="Your Name" required />
<!-- Create age and email fields -->
<input type="submit" value="Submit" />
</form>
<div id="output"></div>
<script>
// Assign action to form when submitted
document.forms['myForm'].onsubmit = () => {
// retrieve submitted values
const name = document.forms['myForm']['name'].value;
// write name linked to an email, followed by the submigged age into output div
// don't actually submit the form to an action
return false;
};
</script>
</body>
</html>