Note: I'm using vanilla js only.
I currently have a working script to add/remove classes via select options
as well localStorage
. All works great, see jsfiddle here.
Now, I'm wanting to add two checkbox's
to perform in the same way. My problem is I'm not sure how to add checkboxes to my current localStorage
script.
Here are my checkbox's
:
<input type="checkbox" name="checkbox1" id="checkbox1" onchange="checkbox1(this)">
<input type="checkbox" name="checkbox2" id="checkbox2" onchange="checkbox2(this)">
My add/remove class on check/uncheck script:
var checkbox = document.getElementById('checkbox1');
checkbox.addEventListener("change", checkbox1, false);
function checkbox1() {
var isChecked = checkbox.checked;
if (isChecked) {
[].map.call(document.querySelectorAll('body,.nc,.tags'), function(el) {
el.classList.add('classname');
});
} else {
[].map.call(document.querySelectorAll('body,.nc,.tags'), function(el) {
el.classList.remove('classname');
});
}
}
Works fine. Now I just need to add them to localStorage
.
Here's my localStorage
script that works for my select options
(full example in my jsfiddle). How do I modify it to work for my checkbox's
as well? I'm assuming I have to modify the second line to check for checkbox
instead of options
but I'm not sure how.
function selectTest(element) {
const a = element.options[element.selectedIndex].value;
setTest(a);
localStorage['test'] = a;
}
function setTest(a) {
if (a == "option1") {
//add+remove classes here
}
}
(function() {
if (localStorage['test'])
document.getElementById("test").value = localStorage['test'];
setTest(localStorage['test'])
})();
Aucun commentaire:
Enregistrer un commentaire