Why Does the Checkbox Stay Checked When Reloading the Page

Checkbox Stays Checked on Page Refresh

See http://weblogs.mozillazine.org/gerv/archives/2006/10/firefox_reload_behaviour.html
(first comment):

It’s done that way on purpose so if you tap the refresh button you
don’t lose your work. There’s an entry in Bugzilla somewhere that’s
been WONTFIXed asking for a regular refresh to always reset the form
entirely. Basically it’s a backwards-compatibility thing — every
browser since NS1.0 (maybe even Mosiac) has done that.

Dynamically-generated pages don’t even reset themselves, though if the
expiration is set to 0 and you hit the back button it will give you a
fresh form. Also, if the form itself changes (add or remove elements,
change the action, etc.) the for will reset on a reload. I haven’t
tested it, but setting the form name to something random (assuming you
don’t need the name for JS access) might just work. Like ”> in PHP.

As you said, forcing a refresh clears the form, and resetting it does
too. Would something like do
what you want (again, not tested)?

Why does the checkbox stay checked when reloading the page?

Yes, I believe it is caching. I see this behaviour on Firefox for example (not Safari, for what that's worth :) ).

you can reload the page and bypass the cache (on Firefox) using CTRL-SHIFT-R and you'll see the check value doesn't carry (a normal CTRL-R will grab the info from the cache however)

edit: I was able to disable this server side on Firefox, setting a cache control header:

Cache-Control: no-store

this seems to disable the "remember form values" feature of Firefox

HTML checkboxes keep checked after refresh

I've found a solution which uses only HTML. If you add the autocomplete="off" attribute to the element it won't set the previous state after refresh..

<input type="checkbox" id="foo" autocomplete="off"/>

How do I keep single checkbox stay checked after refreshing the page?

I think your code is executing before the form elements are loading, so place it at the end of your code or wrap it using document ready handler to execute only after the elements are loaded. If you were placed the code before the element $("#checkbox-container :checkbox") would select nothing since it is not yet loaded in the DOM.

One more thing to do, in your code the checkbox doesn't have any id so add a unique id to the element to make it work since the JSON is generating using the id value.

<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Background Swap: <input type="checkbox" id="name" name="new_background" />
</div>

<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
<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>
</div>

Working demo : FIDDLE


<script>
// document ready handler
// or $(document).ready(Function(){...
jQuery(function($) {
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>
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Background Swap: <input type="checkbox" id="name" name="new_background" />
</div>

<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>

</div>

Working demo : FIDDLE

Keep checked checkboxes after refresh

I think you see that all are checked if one of them are checked because the model does not account for different users.

Try changing the checked variable to take the user's id as a key

checked: {[userId:string]: boolean} = {};

The key (userId) is of type string, and the value is boolean. e.g. checked can be: {someUserId1: false, someUserId2: false, someUserId3: true};

Meaning something like this:
HTML

    <tr scope="row" *ngFor="let user of users">
<td class="w-25">
<input
class="check-btn"
type="checkbox"
name="premium"
[checked]="checked[user.id]"
[ngModel]="checked[user.id]"
(click)="
eventChecked($event.target.checked ? '1' : '0', user.id)
"
/>
</td>
<td class="w-50">{{ user.name }}</td>
</tr>

TS

users: IUser[];
checked: {[userId:string]: boolean} = {}; // the key is of type string, and the value is boolean. e.g. checked can be: {someUserId1: false, someUserId2: false};

constructor(
private userService: UserService,

) {}

ngOnInit(): void {
this.getUsers();
}

getUsers() {
this.userService.getUsers().subscribe(
(data) => {
this.users = data;
console.log(data);
this.users.forEach(e => {
if(e.premium == 1){
this.checked[e.id] = true;
console.log(this.checked);
}
});
},
(error) => {
console.log(error);
}
);
}

eventChecked(event: any, id: number) {
console.log(id, event);
this.checked[id] = true;
this.userService.editUser(event, id).subscribe();
}

I have not tested the code as it is, and you may have to modify it.

Checkboxes stay checked after page refresh

Keep the class on each input, but also give each a unique ID if you wish to have something unique to use in the storage object.

  <input type="checkbox" id="opt1" class="option">

<input type="checkbox" id="opt2" class="option">

<input type="checkbox" id="opt3" class="option">

<input type="checkbox" id="opt4" class="option">

<input type="checkbox" id="opt5" class="option">

<input type="checkbox" id="opt6" class="option">

You can then still select the elements at once by their class, but use the .id to store the items in the object, and to reset them.

  $(".option").on("change", function(){
var checkboxValues = {};

$(".option").each(function(){
checkboxValues[this.id] = this.checked;
});

$.cookie('checkboxValues', checkboxValues, { expires: 1, path: '/' })
});

function repopulateCheckboxes(){
var checkboxValues = $.cookie('checkboxValues');

if(checkboxValues){
Object.keys(checkboxValues).forEach(function(id) {
$("#" + id).prop('checked', checkboxValues[id]);
});
}
}

$.cookie.json = true;
repopulateCheckboxes();

Input checkboxes are unchecking on refresh

You'll have to store the checkbox state somewhere and load it on "document ready" event. You can store the values in browser's local storage.

Here's the untested example that should give you the general idea:

var checkboxes = document.querySelectorAll('input[type="checkbox"]');

// On document ready event, set the initial states of the checkboxes
document.addEventListener('DOMContentLoaded', function () {
checkboxes.forEach(function (checkbox) {
this.checked = window.localStorage.getItem(checkbox.id) || false;
});
});

// When checkbox state is changed, save it to the localStorage
checkboxes.forEach(function (checkbox) {
checkbox.addEventListener('change', function () {
window.localStorage.setItem(this.id, this.value);
});
});

Keep in mind that for this example to work, you'll need unique id for each checkbox, since it's used as localStorage key.

You could also store your checkbox states in the session storage, or even cookies, but the local storage seems the most appropriate for this case. You can read more about it on MDN.

P.S. SO snippets cannot use localStorage due to security reasons, so I can't give you a complete example.



Related Topics



Leave a reply



Submit