Chrome Extensions Options
$(function() {
$('form').first().options();
});
<html>
<head>
<script src="http://code.jquery.com/jquery-2.0.0.min.js" type="text/javascript" language="javascript"></script>
<script src="jquery.chrome.options.js" type="text/javascript" language="javascript"></script>
<script src="options.js" type="text/javascript" language="javascript"></script>
</head>
<body>
<form action="#" method="get" name="options">
<p><label>resolution<select name="q" type="select">
<option value="720">720p</option>
<option value="480">480p</option>
<option value="360">360p</option>
</select></label></p>
<p><label>clean<input name="clean" type="checkbox" /></label></p>
<p><label>last items<input name="last" type="textfield" value/></label></p>
</form>
</body>
</html>
(function($){
$.extend({
json: {
encode: function(obj) {
if (!obj) return '[]';
var json = JSON.stringify(obj);
return json;
},
decode: function(str) {
if (!str) return false;
if (typeof(str) != 'string') return false;
var obj = $.parseJSON(str);
return obj;
}
},
byName: function(name) {
return $('*[name="' + name + '"]');
},
options: {
read: function(k) {
var options = $.json.decode(localStorage['options']);
if (!k) return options;
},
write: function(opt) {
var options = $.json.decode(localStorage['options']);
options = $.extend({}, options, opt);
localStorage['options'] = $.json.encode(options);
},
apply: function(options){
$.each(options, function(k, v){
var elem = $.byName(k);
switch (elem.attr('type')) {
case 'checkbox':
if (v) {
elem.attr({ checked: 'checked' });
} else {
elem.removeAttr('checked');
}
break;
default:
elem.val(v);
break;
}
});
}
}
});
$.fn.read = function(options) {
var settings = $.extend( {
type: null
}, options);
var arr = [],
obj = {};
this.each(function() {
switch ($(this).attr('type')) {
case 'checkbox':
if ($(this).attr('checked')) {
arr.push({ name: $(this).attr('name'), val: true});
obj[$(this).attr('name')] = true;
} else {
arr.push({ name: $(this).attr('name'), val: false });
obj[$(this).attr('name')] = false;
}
break;
default:
arr.push({ name: $(this).attr('name'), val: $(this).val() });
obj[$(this).attr('name')] = $(this).val();
break;
}
});
switch (settings.type) {
case 'object':
return obj;
break;
case 'json':
return $.json.encode(obj);
break;
default:
if (arr.length == 1) return arr[0].val;
return obj;
break;
}
};
$.fn.options = function() {
var form = this,
o = $.options.read();
$.options.apply(o);
form.find('*[name]').change(function(){
switch ($(this).attr('type')) {
case 'checkbox':
if ($(this).attr('checked')) $(this).removeAttr('checked');
else $(this).attr({ checked: 'checked' });
break;
}
var param = $(this).read({ type: 'object' });
$.options.write(param);
O.options = $.options.read();
});
};
// $(function() {
// $('form').first().options();
// });
})(jQuery);