Checkbox is checked even though checked=false

Viewed 3654

I want to uncheck my Checkbox with Javascript, but it didn't work. And then I tried to set the checked property to false directly in HTML, but not even that worked: (I tried checked="false" too...)

My HTML:

<input type="checkbox" id="dateCheckbox" checked=false >
<label for="dateCheckbox"> Keinen Zeitraum angeben</label>

Result:

result

Why is it still checked?

6 Answers

HTML5 does not use true or false for boolean attributes. Boolean attributes are true by specifying the attribute name alone, and a false value is the omission of the attribute.

(For XHTML5, you provide the attribute-name as the value in order to conform to XML's rules for attributes):


So for an unchecked checkbox, change this:

<input type="checkbox" id="dateCheckbox" checked=false >

To this (HTML5 and XHTML5):

<input type="checkbox" id="dateCheckbox">

For a checked checkbox, change this:

<input type="checkbox" id="dateCheckbox" checked=true >

To this (HTML5):

<input type="checkbox" id="dateCheckbox" checked>

or this (XHTML5):

<input type="checkbox" id="dateCheckbox" checked="checked" />

Setting checked attribute to false won't work.

If checked attribute is present on the input element, it doesn't matters what boolean value you give it, input element will always be checked. To make the input element unchecked, you have to remove the checked attribute.

To uncheck the checkbox input element via javascript, you can remove the checked attribute using removeAttribute() method.

Following code snippet unchecks the checkbox after 2 seconds via javascript.

const checkInput = document.querySelector('#dateCheckbox');

setTimeout(() => {
  checkInput.removeAttribute('checked');
}, 2000);
<input type="checkbox" id="dateCheckbox" checked>
<label for="dateCheckbox"> Keinen Zeitraum angeben</label>

Checkbox work this way.

<input type="checkbox" id="dateCheckbox" checked>
<label for="dateCheckbox"> Keinen Zeitraum angeben</label>
<br />
<input type="checkbox" id="dateCheckbox">
<label for="dateCheckbox"> Keinen Zeitraum angeben</label>

It actuially doesn't matter if u have anything in checked only it existense does

For example,

<input type="checkbox" id="dateCheckbox" checked>
<label for="dateCheckbox"> Keinen Zeitraum angeben</label>

But, omitting checked works as expected,

<input type="checkbox" id="dateCheckbox">
<label for="dateCheckbox"> Keinen Zeitraum angeben</label>

Checkout https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox

Unfortunaly, checked is no a boolean value (true or false). If the checked attribute is present in the <input type="checkbox"> tag it will be checked, no matter what you set as value. If you leave it out, it will work accordingly, because checked is not present.

You need remove "checked" attribute to make checkbox uncheck. checked=false|true has no meaning, same as "selected" in select's options

Related