To implement a solution with JavaScript that retains form data when the user turns the page, you can use localStorage
to save the form data and retrieve it when the page loads again.
Step 1: HTML Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form with Local Storage</title>
</head>
<body>
<form id="myForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<br>
<button type="submit">Submit</button>
</form>
<script src="script.js"></script>
</body>
</html>
Step 2: JavaScript to Save and Retrieve Form Data
// script.js
document.addEventListener('DOMContentLoaded', (event) => {
// Retrieve and populate form data from localStorage
const form = document.getElementById('myForm');
const formData = localStorage.getItem('formData');
if (formData) {
const data = JSON.parse(formData);
for (let key in data) {
if (form.elements[key]) {
form.elements[key].value = data[key];
}
}
}
// Save form data to localStorage on form input
form.addEventListener('input', () => {
const data = {};
Array.from(form.elements).forEach(element => {
if (element.name) {
data[element.name] = element.value;
}
});
localStorage.setItem('formData', JSON.stringify(data));
});
// Clear localStorage on form submission
form.addEventListener('submit', (event) => {
localStorage.removeItem('formData');
});
});
Leave a Reply