How to Check/Uncheck CheckBoxes in a Page using jQuery? Example Tutorial (original) (raw)
In the last couple of articles, I have shared a couple of useful jQuery tips like reloading web pages and working with tag selectors. Today, I'll show you how to check or uncheck a particular checkbox using jQuery, one of the most popular JavaScript frameworks. jQuery provides CSS like selectors which can make this kind of task trivial. If you remember, in HTML a checkbox is checked if the "checked" attribute is present and its value is not false, otherwise, it's unchecked. By using jQuery function prop() you can dynamically add this attribute or if present we can change its value i.e. checked=true to make the checkbox checked and checked=false to mark the checkbox unchecked.
Though you should remember that the prop() function is only available from the jQuery 1.6 version and if you are running on a lower jQuery version then you can also use attr() to check/uncheck a particular checkbox.
Some of you might question that should you learn jQuery now, Well, I think you should. Though it has lost some of its charms to Angular, React, and Vue JS but if you are not using those frameworks, jQuery can still be a lifesaver to perform common web development tasks.
Web Development is a constantly changing space but not every project or company adopts them so fast. That's why you find a lot of companies and projects still using jQuery and even plain old HTML with JavaScript.
Btw, if you are new to the web development space, I strongly suggest you go through The Web Developer Bootcamp by Angela Yu at least once. Web Development is a vast area and you need to know a lot of tools and technologies to become a full-stack developer. This course will not only teach you jQuery but also all other important technologies you need to become a better Web Developer.
Anyway, let's just to the task in hand.
How to Check/Uncheck checkboxes using jQuery
Here is a simple jQuery example to show you how to check and uncheck a particular checkbox. In this example, we are selecting one particular checkbox using ID selector, if you want to select multiple checkboxes.
You can also use a class selector if there is a class applied to all the checkboxes or you can also use an element selector like input[type='checkbox'] to select all checkboxes.
Depending on whether you want to apply the change to one element or multiple elements, there are a couple of ways to do it in jQuery. I suggest you check The Complete jQuery Course to see the full list of selectors.
Once the checkbox is selected, we are calling prop() function as prop( "checked", true ) to check the checkbox and prop( "checked", false ) to uncheck the checkbox.
jQuery Example to Select Checkbox
Here is a working example:
How to check/uncheck a checkbox using jQuery