Skip to content

Instantly share code, notes, and snippets.

@keyvanakbary
Last active June 26, 2018 07:09
Show Gist options
  • Save keyvanakbary/628766ca3f127740d4c6 to your computer and use it in GitHub Desktop.
Save keyvanakbary/628766ca3f127740d4c6 to your computer and use it in GitHub Desktop.
Jquery plugin for temp drafts in forms
/*global $,localStorage*/
$.fn.draft = function () {
'use strict';
if (!localStorage) {
return;
}
var form = $(this),
fields = form.find('input,select,textarea'),
keyFor = function (field) {
return form.attr('id') + $(field).attr('name');
},
clearFields = function () {
fields.each(function (index, field) {
localStorage.removeItem(keyFor(field));
});
},
saveField = function () {
localStorage.setItem(keyFor(this), $(this).val());
},
recoverField = function (index, field) {
var value = localStorage.getItem(keyFor(field));
if (value) {
$(field).val(value);
}
};
form.on('submit', clearFields);
fields.on('change', saveField).each(recoverField);
};
@keyvanakbary
Copy link
Author

jQuery Draft Plugin

Remember changes on form fields by saving them on localStorage
jQuery Draft

Usage

You will need a modern browser with localStorage support and jQuery

<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="jquery-draft.js"></script>
<script>
    $('form').draft();
</script>

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