PDA

View Full Version : Resolved Uncheck all checkboxes and clear localStorage at the same time.



qwikad.com
09-08-2015, 01:27 PM
I think I am close to where I want to be, but I still need help. How can I uncheck all checkboxes and clear localStorage for those checkboxes at the same time? Right now it unchecks them, but localStorage isn't actually cleared:

http://jsfiddle.net/T5Pm7/233/


//Adds to LocalStorage

(function() {
var boxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < boxes.length; i++) {
var box = boxes[i];
if (box.hasAttribute("store")) {
setupBox(box);
}
}

function setupBox(box) {
var storageId = box.getAttribute("store");
var oldVal = localStorage.getItem(storageId);
console.log(oldVal);
box.checked = oldVal === "true" ? true : false;

box.addEventListener("change", function() {
localStorage.setItem(storageId, this.checked);
});
}
})();


//Uncheck all

document.getElementById('selections').addEventListener('change', function(e) {
var el = e.target;
var inputs = document.getElementById('selections').getElementsByTagName('input');

if (el.id === 'all') {

if (el.checked) {

for (var i = 1, input; input = inputs[i++]; ) {
input.checked = false;
}
}
}

else {
inputs[0].checked = false;
}
}, false);



//Checkbox selections


(function(d) {

function nodeFlush(e) {
while (e.firstChild) e.removeChild(e.firstChild);
}

function nodeAdd(e, node) {
e.appendChild(typeof node == 'object' ? node : d.createTextNode(node));
}

function nodeReplace(e, node) {
nodeFlush(e);
nodeAdd(e, node);
}

function eventAdd(e, eventName, handler) {
if (e.addEventListener) e.addEventListener(eventName, handler, false);
else e.attachEvent('on' + eventName, handler);
}

var
target = d.getElementById('selections'),
output = d.getElementById('selectionsResults'),
inputs = target.getElementsByTagName('input');

function checkInputs() {
var result = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) result.push(inputs[i].value);
}
nodeReplace(output, result.length ? result.join(', ') : 'nothing');
document.getElementById('selectionsResults').innerHTML=document.getElementById('selectionsResults').textContent;

}

for (var i = 0; i < inputs.length; i++) {
eventAdd(inputs[i], 'change', checkInputs);
eventAdd(inputs[i], 'click', checkInputs);

}

checkInputs();

})(document);

molendijk
09-08-2015, 02:34 PM
Just add localStorage.clear()

//Uncheck all

document.getElementById('selections').addEventListener('change', function(e) {
var el = e.target;
var inputs = document.getElementById('selections').getElementsByTagName('input');

if (el.id === 'all') {

if (el.checked) {

for (var i = 1, input; input = inputs[i++]; ) {
input.checked = false;
localStorage.clear();
}
}
}

else {
inputs[0].checked = false;
}
}, false);

qwikad.com
09-08-2015, 04:46 PM
Great, thank you!