Borislav Hadzhiev
Thu Mar 31 2022·2 min read
Photo by Averie Woodard
To set a checkbox to checked/unchecked in TypeScript:
HTMLInputElement
using a type assertion.checked
property to set the checkbox to checked or
unchecked.This is the index.html
file for the examples in this article.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> </head> <body> <input type="checkbox" name="subscribe" id="subscribe" /> <script src="./src/index.ts"></script> </body> </html>
And here is the related TypeScript code.
const checkbox = document.getElementById( 'subscribe', ) as HTMLInputElement | null; if (checkbox != null) { // ✅ Set checkbox checked checkbox.checked = true; // ✅ Set checkbox unchecked // checkbox.checked = false; }
We used a type assertion to type the checkbox
variable as HTMLInputElement
or null
.
If you're working with an option or select element, you can use the
HTMLOptionElement
or HTMLSelectElement
types.
The reason we included null
in the type is because the
document.getElementById
method will return null
if no element with the provided id
is found in the
DOM.
checkbox
variable does not store a null
value before accessing its checked
property.Once we enter the if
block, TypeScript knows that the type of the checked
variable is HTMLInputElement
and not HTMLInputElement | null
.
null
from the type in the type assertion.Now we are able to access the checked
property on the element, because we've
typed it correctly. The property can be used to read or set the checked state of
the checkbox element.
If you need to uncheck the checkbox, set its checked
property to false
.
const checkbox = document.getElementById( 'subscribe', ) as HTMLInputElement | null; if (checkbox != null) { // ✅ Set checkbox checked checkbox.checked = true; // 👇️ true console.log(checkbox.checked); // ✅ Set checkbox unchecked checkbox.checked = false; }
It's always a best practice to include null
in the type assertion, because the
getElementById
method would return null
if no element with the provided id
was found.