Last active
August 29, 2015 14:18
-
-
Save krizpoon/fe7fd66e2b2fef2e9637 to your computer and use it in GitHub Desktop.
User options with local storage
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); }); | |
} |
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
var options = new PageOptions('PageKey'); | |
$('form.form1 input[name=field1]').bindToOptions(options); | |
$('form.form1 select[name=field2]').bindToOptions(options); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment