Check if an HTML Checkbox is checked using Javascript

0 min read 131 words

While processing forms in web development, it’s a common requirement to be able to tell if a checkbox has been checked or not.

It’s not immediately obvious though. Let’s dispell this and provide some ways to check if a checkbox is checked using Javascript.

First, we need an HTML checkbox to play around with.

<input type="checkbox" class="myCheckbox" />

Using Javascript

Using regular Javascript, we can tell if it is checked by using the following Javascript:

document.querySelector(".myCheckbox").checked

You can also use a Query Selector Pattern to tell if a value matches as follows:

var checked = document.querySelector(".myCheckbox:checked")!==null ? true: false;

Using jQuery

jQuery comes with quite a nice way to do this using the is() method.

if ( $(".myCheckbox").is(":checked") ) {
    // Is checked
} else {
    // Is NOT checked
}
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags