I am studying how to keep checkboxs stay checked after refreshing the page.
And I find this helps.
However, the code, does not work right at my server. When I refresh, checkboxs stayed unchecked.
I also use this compiler. NOT GOOD.
See
The code I use:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#checkbox-container{
margin: 10px 5px;
}
#checkbox-container div{
margin-bottom: 5px;
}
#checkbox-container button{
margin-top: 5px;
}
input[type=text] {
padding: .5em .6em;
display: inline-block;
border: 1px solid #ccc;
box-shadow: inset 0 1px 3px #ddd;
border-radius: 4px;
}
</style>
</head>
<body>
<div id="checkbox-container">
<div>
<label for="option1">Option 1</label>
<input type="checkbox" id="option1">
</div>
<div>
<label for="option2">Option 2</label>
<input type="checkbox" id="option2">
</div>
<div>
<label for="option3">Option 3</label>
<input type="checkbox" id="option3">
</div>
</div>
</body>
</html>
<script>
var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
$checkboxes = $("#checkbox-container :checkbox");
$checkboxes.on("change", function(){
$checkboxes.each(function(){
checkboxValues[this.id] = this.checked;
});
localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
});
// On page load
$.each(checkboxValues, function(key, value) {
$("#" + key).prop('checked', value);
});
</script>
It seems to me that the code only works on CODEPEN.
May somebody tells me what is wrong?
Thanks a lot.
2
Answers
The code you provided has a couple of issues:
The script tag is placed outside the HTML body. Move the script tag inside the body or wrap the JavaScript code in a proper script block.
The jQuery library is not included in the code. To use jQuery functions like $(), you need to include the jQuery library before using it.
Why not use a
fieldset
and track changes to the entire thing?I’ve also genericized the listener so that it can easily be modified to handle more fieldsets as well as other
input
types.input type="text"
support added as an example.