24. Autosave

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
/* For today’s project, we’re going to write a script
that automatically saves form field data as a user types. */

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