HTML and CSS Reference
In-Depth Information
16. Copy the code that you used to fetch the form fields in your saveData() function to the new popu-
lateForm() function.
// Attempt to populate the form using data stored in
LocalStorage.
function populateForm() {
// Fetch the input elements.
var name = document.getElementById(“name");
var phone = document.getElementById(“phone");
var email = document.getElementById(“email");
}
17. Set the value property of each of these three inputs using the data stored in LocalStorage. You can use the
getItem(key) function to retrieve data from the datastore. If no contact data has been saved yet, the
getItem() function returns null . Most browsers recognize that null is not the desired value and won't
update the value of the input. However, Internet Explorer will populate the fields with the string null . This
means that you need to first check that the result of getItem() is not null before updating an input's
value. Use multiple if statements to do this.
// Attempt to populate the form using data stored in
LocalStorage.
function populateForm() {
// Fetch the input elements.
var name = document.getElementById(“name");
var phone = document.getElementById(“phone");
var email = document.getElementById(“email");
// Retrieve the saved data and update the values of the
// form fields.
if (localStorage.getItem(“name") != null) {
name.value = localStorage.getItem(“name");
}
if (localStorage.getItem(“phone") != null) {
phone.value = localStorage.getItem(“phone");
}
if (localStorage.getItem(“email") != null) {
email.value = localStorage.getItem(“email");
}
}
18. To finish up, add a call to the populateForm() function at the top of the window.onload event
listener.
window.onload = function() {
// Check for LocalStorage support
if (localStorage) {
// Populate the form fields
populateForm(form);
...
}
}
19. Save the storage.js file.
Search WWH ::




Custom Search