How to make a checkbox without a form with HTML and JavaScript?

Sometimes, we want to make a checkbox without a form with HTML and JavaScript.

In this article, we’ll look at how to make a checkbox without a form with HTML and JavaScript.

How to make a checkbox without a form with HTML and JavaScript?

To make a checkbox without a form with HTML and JavaScript, we can add an input element with type checkbox.

Then we can get its value when we check or uncheck it by attaching a change event handler to it.

For instance, we write:

<input type="checkbox" />

to add an input with the type attribute set to checkbox to add a checkbox.

Then we write:

const input = document.querySelector('input')
input.onchange = (e) => {
  console.log(e.target.checked)
}

to select the input with querySelector.

Then we set the input.onchange property to a function that gets the checked value of the checkbox from e.target.checked.

Conclusion

To make a checkbox without a form with HTML and JavaScript, we can add an input element with type checkbox.

Then we can get its value when we check or uncheck it by attaching a change event handler to it.