How to remember checkbox value when reloading in php

Started by
4 comments, last by Brainx7 9 years, 10 months ago

so on form.php I have <input type="checkbox" name="check" >

on forminput.php <?php if (isset($_GET['check'])) {echo "<input type='checkbox' checked disabled>";}else{echo"<input type='checkbox' disabled>";}?>

so I want that when I refresh or go back one page to form.php the checkbox value is remembered

Advertisement

"go back" like pressing the back button in the browser? When you press the back button the browser won't do a new request, it will look at the cached page and that page will have the previous value (every input will look the same). The best solution I can think in that case would be to use JavaScript and save the checkbox value in sessionStorage when you change it. Then in both pages make a JavaScript interval (setInterval) that checks sessionStorage and updates the checkbox value with whatever is stored.

Also, a suggestion for your code... you can simplify a lot the second line you posted and make it more readable and less prone to bugs. Change it to:


<input type="checkbox" <?php echo (isset($_GET['check']) ? 'checked' : '');?> disabled>

I found this code but It won't work on php only html, <!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Persist checkboxes</title>
</head>

<body>
<div>
<label for="checkAll">Check all</label>
<input type="checkbox" id="checkAll">
</div>
<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>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>

<script>
$("#checkAll").on("change", function() {
$(':checkbox').not(this).prop('checked', this.checked);
});

That's just a code to do a "check all" checkbox that checks the other checkboxes on the page, it has nothing to do with your question.

EDIT: And it has nothing to do with my response, did you read it? Did you really meant "pressing the browser's back button" like I assumed?

That's just a code to do a "check all" checkbox that checks the other checkboxes on the page, it has nothing to do with your question.

EDIT: And it has nothing to do with my response, did you read it? Did you really meant "pressing the browser's back button" like I assumed?

dude, yes that code checks all, but it retains the values when refreshed or going back ,whatever, which is what i'm looking for

I found a solution here http://jsfiddle.net/TzPW9/380/

This topic is closed to new replies.

Advertisement