JavaScript

How to check if a checkbox is checked? (with JavaScript or jQuery)

April 26, 2022

How to check if a checkbox is checked? (with JavaScript or jQuery)

In this article you will learn how to check if a checkbox is checked – both with pure JavaScript and using the jQuery lib.

check if a checkbox is checked thumb

What’ up programmer, how are you? Let’s learn how to identify if a checkbox is marked with JavaScript!

First I would like to present to you the way we can use to check the checkbox with pure JavaScript

It is preferable to opt for it, so as not to need an external dependency to check this input, thus making your code lighter and also more performant.

Let’s go to the example:

<input type="checkbox" id="terms" name="terms">
<label for="terms">Do you confirm you read the contract?</label>

This will be our reference HTML, now look at the JavaScript:

let checkbox = document.getElementById('terms');

if(checkbox.checked) {
 console.log("The checkbox is checked");
} else {
 console.log("The checkbox is not checked");
}

Just selecting the checked property can we show whether the checkbox input is checked or not

See how simple it is! That’s why I always like to check how to do something natively in the languages, and then look for solutions from external libs

Let’s see now in jQuery:

let checkbox = $('#terms');

if(checkbox.is(":checked")) {
 console.log("The checkbox is checked");
} else {
 console.log("The checkbox is not checked");
}

Note that the biggest gain is the element selection, however in jQuery the way to do this check is through the is method

Conclusion

In this article we learned how to check if a checkbox is checked

We use two ways, the first with Vanilla JavaScript, which is the most suitable

And later we use the form with jQuery

Do you want to learn more about JavaScript and web development? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x