Skip to content

Instantly share code, notes, and snippets.

@fetimo
Created February 18, 2012 17:54
Show Gist options
  • Save fetimo/1860383 to your computer and use it in GitHub Desktop.
Save fetimo/1860383 to your computer and use it in GitHub Desktop.
A quick way to attach a progress meter to checked inputs and store them locally
(function() {
var inputs = document.getElementsByTagName('input'),
j = inputs.length,
checkedBoxes = 0;
//adds click event listener to each input
for (var i = 0; i < j; i += 1) {
inputs[i].addEventListener("click", function(){changeState(this);});
if (inputs[i].checked == true) checkedBoxes += 1;
}
function calculatePercentage() {
var checkedBoxes = 0,
percent = document.getElementsByTagName('progress')[0]; //assumes the progress meter we're using is the first one in the DOM
for (var i = 0; i < j; i += 1) {
if (inputs[i].checked === true) checkedBoxes += 1;
}
percent.value = checkedBoxes;
percent.max = j;
}
var storage = localStorage.getItem('checked');
if (storage != null) {
var items = localStorage.getItem('checked').split(',');
for (var k = 0; k < j; k += 1) {
//for each input node, check if the name matches the name in the localstorage
for (var l = 0; l < j; l += 1) {
if (items[l] == inputs[k].id) {
//we found a match! set it to checked
inputs[k].checked = true;
}
}
}
}
function changeState(input) {
//delete from storage where id == input id
var storage = localStorage.getItem('checked');
if (input.checked === true) {
storage === null ? localStorage.setItem('checked', input.id + ',') : localStorage.setItem('checked', storage + input.id + ',');
} else {
var re = new RegExp(input.id + ',', 'g'),
newStorage = storage.replace(re, "");
localStorage.setItem('checked', newStorage);
}
calculatePercentage();
}
calculatePercentage();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment