Skip to content

Instantly share code, notes, and snippets.

@hanigamal
Last active December 18, 2015 13:09
Show Gist options
  • Save hanigamal/5788020 to your computer and use it in GitHub Desktop.
Save hanigamal/5788020 to your computer and use it in GitHub Desktop.
jquery functions for record
function load(_this, init){
var name = generateName(_this);
var type = _this.attr('type');
if(!type)
type = _this.prop("tagName");
if(!init && type != 'radio' && type != 'checkbox')
localStorage.setItem(name, _this.val())
value = localStorage.getItem(name);
if(type == 'radio'){
if(!init){
clearByName(_this.attr('name'));
localStorage.setItem(name, 'checked')
_this.attr('checked','checked');
}else{
if(value == 'checked'){
_this.attr('checked','checked');
}
}
}else if(type == 'select'){
if(!init){
clearByName(_this.attr('name'));
localStorage.setItem(name, _this.is(":selected").text())
_this.val( _this.find(":selected").text());
}else{
_this.val( _this.find(":selected").text());
}
}else if(type == 'checkbox'){
if(!init){
if(_this.is(':checked')){
localStorage.setItem(name, 'checked');
}else{
localStorage.setItem(name, '');
_this.val(_this.attr('checked',''));
}
}else{
if(value == 'checked')
_this.val(_this.attr('checked','checked'));
}
}else{
_this.val(value);
}
}
function generateName(_this){
var name = 'record';
if(_this.attr('class')) name += _this.attr('class');
if(_this.attr('name')) name += _this.attr('name');
if(_this.attr('id')) name += _this.attr('id');
if(_this.attr('type') == 'radio') name += _this.attr('value');
if(_this.attr('type') == 'checkbox') name += _this.attr('type');
name = $.trim(name);
return name;
}
function clearByName(name){
var matcher = new RegExp(name);
Object.keys(localStorage).forEach(function(key){
if (matcher.test(key)) {
localStorage.removeItem(key);
}
});
//console.log('Reset '+name);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment