Last active
August 29, 2015 14:15
-
-
Save krizpoon/3ff93852a82f1c87191f to your computer and use it in GitHub Desktop.
Local storage and binding to form fields (extending jQuery)
This file contains hidden or 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
function PageOptions (pageKey) | |
{ | |
var values = {}; | |
if (window.localStorage) | |
{ | |
var json = window.localStorage.getItem(pageKey); | |
try | |
{ | |
values = JSON.parse(json); | |
} | |
catch (ignored) {} | |
} | |
if (!values) values = {}; | |
this.get = function(key) | |
{ | |
return values[key]; | |
}; | |
this.put = function(key, value) | |
{ | |
values[key] = value; | |
return this; | |
}; | |
this.save = function() | |
{ | |
if (!window.localStorage || !JSON || !JSON.stringify) return this; | |
var json = JSON.stringify(values); | |
window.localStorage.setItem(pageKey, json); | |
return this; | |
} | |
this.applyValue = function(key, element) | |
{ | |
var val = this.get(key); | |
if (val) element.val(val); | |
return this; | |
} | |
} | |
$.fn.saveValue = function(options) | |
{ | |
var name = this.attr('name'); | |
if (!name || !options || !options.put || !options.save) return this; | |
var value; | |
if (this.is('[type=checkbox]')) | |
{ | |
value = this.prop('checked'); | |
} | |
else | |
{ | |
value = this.val(); | |
} | |
options.put(name, value).save(); | |
return this; | |
}; | |
$.fn.loadValue = function(options) | |
{ | |
var name = this.attr('name'); | |
if (!name || !options || !options.get) return this; | |
var value = options.get(name); | |
if (this.is('[type=checkbox]')) | |
{ | |
this.prop('checked', !!value); | |
} | |
else | |
{ | |
this.val(value); | |
} | |
return this; | |
} | |
$.fn.bindToOptions = function(options) | |
{ | |
return this.loadValue(options).change(function(){ $(this).saveValue(options); }); | |
} | |
// Usage | |
var options = new PageOptions('unique-code-for-this-page'); | |
$('form input[name=somefield]').bindToOptions(options); | |
$('form input[name=anotherfield]').bindToOptions(options); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment