How can I create multiple checkboxes that stay either stay checked or unchecked on browser refresh depending on what I choose using javascript? I figured out how to do one checkbox, but when I tried to add another checkbox the initial checkbox wouldn't remember that it had been checked on the refresh (if that makes sense lol). Please help. Here's my code:
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div id="checkbox-container">
<input type="checkbox" id="name"/>
</div>
</div>
<script>
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function() {
$checkbox.each(function() {
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value) {
$("#" + key).prop('checked', value);
});
</script>
<style>
.wrap input {
position: absolute;
top: 300px;
left: 500px;
}
input[type=checkbox] {
transform: scale(2);
margin: 10px;
cursor: pointer;
}
.wrap {
filter: hue-rotate(410deg);
}
</style>
<body>
</body>
</html>
Aucun commentaire:
Enregistrer un commentaire