Skip to content

Instantly share code, notes, and snippets.

@bradymholt
Last active November 22, 2022 13:23
Show Gist options
  • Save bradymholt/76c10297bb82449b067388d2ad236038 to your computer and use it in GitHub Desktop.
Save bradymholt/76c10297bb82449b067388d2ad236038 to your computer and use it in GitHub Desktop.
Backup textarea in localStorage
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<script>
const issueId = window.location.search; // TODO: clean up parsing of issue id
const formTextLocalStorageKey = `formText_${issueId}`;
document.addEventListener("DOMContentLoaded", function () {
restoreDraftFormText();
getFormTextElement().addEventListener("keyup", (event) => {
saveDraftFormText();
});
});
function restoreDraftFormText() {
const formTextElement = getFormTextElement();
var backedUpIssueTextValue = localStorage.getItem(formTextLocalStorageKey);
if (backedUpIssueTextValue && !formTextElement.value) {
formTextElement.value = backedUpIssueTextValue;
}
}
function saveDraftFormText() {
var issueTextValue = getFormTextElement().value;
localStorage.setItem(formTextLocalStorageKey, issueTextValue);
}
function getFormTextElement() {
return document.getElementById("formText");
}
</script>
<body>
<fieldset>
<legend>Form</legend>
<form>
<textarea id="formText" name="formText" cols="40" rows="4"></textarea>
<div>
<button type="submit">Submit</button>
</div>
</form>
</fieldset>
</body>
</html>
@bradymholt
Copy link
Author

Google Chrome_2022 _11_21T23 12 41Z

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment