25. Autosave - Single Entry

Fill the form below.

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<p>Fill the form below.</p>
<form class="save-me" id="save-me" autocomplete="off">
<label class="label" for="name">Name</label>
<input class="input" type="text" name="name" id="name" autocomplete="off">
<label class="label" for="address">Address</label>
<input class="input" type="text" name="address" id="address">
<label class="label" for="email">Email</label>
<input class="input" type="email" name="email" id="email">
<label class="label" for="more">Additional thoughts?</label>
<textarea class="textarea" name="more" id="more"></textarea>
<p>
<button class="button" type="submit">Submit</button>
</p>
</form>

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* Modify the script to store all of the fields into a single array or object
that you save and retrieve from locationStorage. To avoid conflicts with yesterday’s project,
you might want to give the localStorage item a different key name. */

const form = document.querySelector('#save-me');
function saveInputValue (e) {
let savedInputs = localStorage.getItem('form-inputs');
savedInputs = savedInputs ? JSON.parse(savedInputs) : {};
savedInputs[e.target.id] = `${e.target.value}`;
localStorage.setItem('form-inputs', JSON.stringify(savedInputs));
}
function getInputsFromLocalStorage () {
let inputs = Array.prototype.slice.call(document.querySelectorAll('[data-type="input"]'));
let savedInputs = localStorage.getItem('form-inputs');
savedInputs = savedInputs ? JSON.parse(savedInputs) : {};
inputs.forEach(function(input) {
if (!savedInputs[input.id]) return;
input.value = savedInputs[input.id];
})
}
function clearDataOnSubmit () {
localStorage.clear();
}
form.addEventListener('input', saveInputValue);
form.addEventListener('submit', clearDataOnSubmit);
getInputsFromLocalStorage ();