Last active
November 16, 2022 23:36
-
-
Save angusgrant/d421885a7ccb51d22871025d9e2f05a1 to your computer and use it in GitHub Desktop.
week 5 lesson2 save all form data as one String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Form Autosave</title> | |
<style type="text/css"> | |
body { | |
margin: 1em auto; | |
max-width: 40em; | |
width: 88%; | |
} | |
label, | |
input, | |
textarea { | |
display: block; | |
width: 100%; | |
} | |
input, | |
textarea { | |
margin-bottom: 1em; | |
} | |
textarea { | |
height: 8em; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>Form Autosave - Single Entry</h1> | |
<form id="save-me"> | |
<label for="name">Name</label> | |
<input type="text" name="name" id="name"> | |
<label for="address">Address</label> | |
<input type="text" name="address" id="address"> | |
<label for="email">Email</label> | |
<input type="email" name="email" id="email"> | |
<label for="more">Additional thoughts?</label> | |
<textarea name="more" id="more"></textarea> | |
<p> | |
<button type="submit">Submit</button> | |
</p> | |
</form> | |
<script> | |
const form = document.querySelector('#save-me'); | |
const inputs = form.elements; | |
function loadDataFromStorage() { | |
//populate inputs and text area on load from local storage if it exits. | |
const retrievedDataObject = JSON.parse(localStorage.getItem('allFormData')); | |
if (retrievedDataObject) { | |
//iterate over object props i looked this up here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in | |
for (let key in retrievedDataObject){ | |
//set form field value from saved Object | |
//field uses field.['name'].value | |
inputs[key].value = retrievedDataObject[key]; | |
} | |
} | |
} | |
function storeEdits() { | |
//create an empty Obj for the storing of all form inputs | |
const updatedDataObject = {}; | |
//write inputs to object | |
form.addEventListener('input', function (event) { | |
if (event.target.matches('input,textarea')) { | |
updatedDataObject[event.target.id] = event.target.value; | |
localStorage.setItem('allFormData', JSON.stringify(updatedDataObject)); | |
} | |
}); | |
} | |
loadDataFromStorage(); | |
storeEdits(); | |
//on submitting the form clear out local storage. | |
form.addEventListener('submit', function () { | |
localStorage.removeItem('allFormData'); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment