Reputation: 31
I am unable to persist checkbox checked after page is refreshed.
Upvotes: 1
Views: 9038
Reputation: 11
Here how I do it:
<html>
<input type="checkbox" <?php echo file_get_contents(".cktest"); ?> onclick="getFileFromServer('write_ckfile.php?target=.cktest&value='+this.checked, function(text){ show_write(text)});"> cktest with php<br/>
<!-- with ajax read the checked attribut from file -->
<input id="withajax" type="checkbox" onclick="getFileFromServer('write_ckfile.php?target=.cktest&value='+this.checked, function(text){ show_write(text)});"> cktest with ajax<br/>
<script>
function getFileFromServer(url, doneCallback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
}
function show_write(text) {
//alert(text);
}
//
getFileFromServer(".cktest", function(x) { document.getElementById("withajax").checked=x;} );
</script>
</html>
and the file write_ckfile.php:
<?php
$strtarget=$_GET['target'];
$status=$_GET['value']=="true"?"checked":"";
file_put_contents($strtarget, $status );
?>
I hope this helps. MiKL~
Upvotes: 0
Reputation: 36703
You need to use cookies for this... As soon as user clicks on check box, store its state into a cookie and just fetch the cookie value on page load to prepoulate the checkboxes as they were in previous selection.
HTML
<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>
<button>Check all</button>
Fetching checkboxes value and making a cookie out of them
var checkboxValues = {};
$(":checkbox").each(function(){
checkboxValues[this.id] = this.checked;
});
$.cookie('checkboxValues', checkboxValues, { expires: 7, path: '/' })
Function to read cookies to prepopulate on load
function repopulateCheckboxes(){
var checkboxValues = $.cookie('checkboxValues');
if(checkboxValues){
Object.keys(checkboxValues).forEach(function(element) {
var checked = checkboxValues[element];
$("#" + element).prop('checked', checked);
});
}
}
Upvotes: 3
Reputation: 14840
You have to do this on server side. Either with PHP, ASP.NET or whatever you use.
This is the only way.
Or, if your website is client-side only, then you would have to implement it without any page refreshing.
Upvotes: 0