Last active
November 22, 2022 13:23
-
-
Save bradymholt/76c10297bb82449b067388d2ad236038 to your computer and use it in GitHub Desktop.
Backup textarea in localStorage
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 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> |
Author
bradymholt
commented
Nov 21, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment