HTML and CSS Reference
In-Depth Information
10. Inside the function block of this event listener, add a call to saveData(form) . You create this function
in the next step.
form.addEventListener(“submit", function(e) {
saveData(form);
});
11. At the bottom of the storage.js file, create a new function called saveData() .
window.onload = function() {
...
}
// Save the form data in LocalStorage.
function saveData() {
}
12. You now need to get the values from the Name, Phone, and Email <input> elements. Within the
saveData() function, create three new variables ( name , phone , and email ), and initialize them by
fetching the <input> elements using their IDs.
function saveData() {
// Fetch the input elements.
var name = document.getElementById(“name");
var phone = document.getElementById(“phone");
var email = document.getElementById(“email");
}
13. Now that you have references to the <input> elements, you can get their values and store them in
LocalStorage. Use the setItem() function to store the values.
function saveData() {
// Fetch the input elements.
var name = document.getElementById(“name");
var phone = document.getElementById(“phone");
var email = document.getElementById(“email");
// Store the values.
localStorage.setItem(“name", name.value);
localStorage.setItem(“phone", phone.value);
localStorage.setItem(“email", email.value);
}
14. You have now added all the code needed to store a user's contact details when the form is submitted. Save
the storage.js file and try submitting some data using the bookings form. If you go back to the Book-
ings page, you can use the developer tools console to check that data is being stored correctly. Use the
localStorage.getItem(key) function you learned about earlier in this chapter to retrieve the data.
15. Write code to populate the form fields with the data in LocalStorage when the page loads. Create a new
function called populateForm() below the saveData() function:
// Attempt to populate the form using data stored in
LocalStorage.
function populateForm() {
}
Search WWH ::




Custom Search