Set a Checkbox to Checked/Unchecked using TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 31, 2022

banner

Photo from Unsplash

Set a Checkbox to Checked/Unchecked using TypeScript #

To set a checkbox to checked/unchecked in TypeScript:

  1. Select the checkbox element.
  2. Type the element as HTMLInputElement using a type assertion.
  3. Use the element's checked property to set the checkbox to checked or unchecked.

This is the index.html file for the examples in this article.

index.html
<!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.

src/index.ts
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.

We make sure that the 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.

If you are certain that the element will exist in the DOM, you can omit 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.

src/index.ts
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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.