Forms will capture most of the data your user inputs. Making sure that data is formatted correctly is essential.
Forms have special properties in HTML5 that make your life easier.
<input type="number"
min="0"
max="84"
step="7"
value="7">
Much elegant, very date-picker. Wow.
<input type="date">
<input type="color">
<input type="search">
<input type="email">
<input type="url">
<input type="tel">
<input type="number">
<input type="date">
<input type="time">
<input type="datetime">
<input type="range">
<input type="color">
In class:
10 Minutes To Explore
<form validate>
<input type="email">
<input type="submit" value="Submit">
</form>
<form novalidate>
<input type="email">
<input type="submit" value="Submit">
</form>
<input type="text" required>
<input type="number" disabled>
<input type="checkbox" checked>
Make sure a field is filled out
Don't allow the user to change a field
Set to be checked by default
let myForm = document.getElementsByTagName("form")[0]
myForm.addEventListener("submit", function(evt){
console.log (myForm.elements[0].value);
})
let myForm = document.getElementsByTagName("form")[0]
myForm.addEventListener("submit", function(evt){
evt.preventDefault()
console.log (myForm.elements[0].value);
})
Stop default behavior
let myForm = document.getElementsByTagName("form")[0];
myForm.addEventListener("submit", function(evt){
evt.preventDefault()
console.log (document.forms[0][0].value);
console.log (myForm.elements[0].value);
console.log (document.getElementById('name').value);
})
Multiple ways to access form data
Note: If you have more than 1 field in your form, you need a submit element!
Create a form with two text fields (name, age)
Bind an event handler to the form's submit action
Insert the form values to the page in a p tag
Validate the form so it can't be blank
BONUS: Insert an error message into the DOM in a P tag if name field contains a non-letter character or if age field contains a non-digit character (RegEx)
let myForm = document.getElementsByTagName("form")[0];
myForm.addEventListener("submit", function(evt){
evt.preventDefault()
document.getElementById('errors').innerText =
`${myForm.elements[0].value}, ${myForm.elements[1].value}`;
} else {
document.getElementById('errors').innerText =
"Name and/or Age fields are incorrect"
}
})
The whole !#
let myForm = document.getElementsByTagName("form")[0];
myForm.addEventListener("submit", function(evt){
evt.preventDefault()
let nameValidates = !/[^A-Za-z]/ig.test(myForm.elements[0].value)
let ageValidates = !/[^\d]/ig.test(myForm.elements[1].value)
if (nameValidates && ageValidates) {
document.getElementById('output-text').innerText =
`${myForm.elements[0].value}, ${myForm.elements[1].value}`;
} else {
document.getElementById('output-text').innerText =
"Name and/or Age fields are incorrect"
}
})