Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML checkboxes keep checked after refresh [duplicate]

Tags:

html

checkbox

I have a couple of check boxes in my markup.. For example:

<input type="checkbox" id="someCheckbox"/>

If I refresh the page with Ctrl+Shift+R everything is OK - the page renders unchecked check boxes, however if some of them were checked and I refresh with F5 they stay in their previous state.

Setting the checked attribute doesn't work since having the attribute is enough to make it checked, the value is more or less irrelevant..

How can I force them to be unchecked on page load, please?

like image 448
Dropout Avatar asked Apr 11 '16 10:04

Dropout


People also ask

How do I keep a checkbox checked in HTML?

The checked attribute is a boolean attribute. When present, it specifies that an <input> element should be pre-selected (checked) when the page loads. The checked attribute can be used with <input type="checkbox"> and <input type="radio"> . The checked attribute can also be set after the page load, with a JavaScript.

Why does the checkbox stay checked when reloading the page?

It means that the checkbox should be empty based on what you are trying to do. However if you were to click the box and reload the page your checked will be true however your input will not be checked. So the issue lies in how you are setting your DOM element to be in a checked state.

How do I make a checkbox automatically checked?

Add checked = "checked" to the input you want selected. For XHTML the recommended way is as described. Check HTML manual and W3C to confirm. The markup posted isn't XHTML, so it's logical to use just the simple keyword attribute checked .


2 Answers

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"/>
like image 129
Dropout Avatar answered Oct 30 '22 08:10

Dropout


You could set them back with javascript

var elements = document.getElementsByTagName("INPUT");
for (var inp of elements) {
    if (inp.type === "checkbox")
        inp.checked = false;
}
like image 34
Bálint Avatar answered Oct 30 '22 10:10

Bálint