CodersTechZone
  • .NET
    • C#
    • ASP.Net
  • HTML
  • Javascript
  • CSS
  • Database
    • SQL Server
    • MYSql
    • Oracle
  • AI
  • TechNews
  • Web-Stories

JavaScript Check and Uncheck Checkbox: Toggle in Seconds

Shawpnendu Bikash Maloroy

July 9, 2024
JavaScript Check and Uncheck Checkbox: Toggle in Seconds
Spread the love

JavaScript Check and Uncheck Checkbox: means allow users to select or deselect options. These tiny input boxes play a key role in making interactive and user-friendly web applications. In this blog post, we are going to manipulate checkboxes status using JavaScript. From a new coder to an experienced JavaScript developer, this guide will cover everything that you need to know.

Table of Contents

  • Why use JavaScript for checkboxes?
  • Basic HTML Checkbox
  • Checking a Single Checkbox with JavaScript
    • Code Example
  • Unchecking a Single Checkbox with JavaScript
    • Code Example
  • JavaScript Check and Uncheck Checkbox: Toggle Single Checkbox State
    • Code Example
  • JavaScript Check and Uncheck Checkbox: Checking Multiple Checkboxes
    • Check Uncheck Checkboxes by Name
    • Output
    • Check Uncheck Checkboxes by Class Name
    • JS Check Checkbox Based on Condition
    • Output: JS Check Checkbox
  • Table of Common Methods
    • Advanced Techniques
    • Using Event Listeners
    • Handling Checkbox Change Events
    • Output Based on User Click
  • Conclusion

Why use JavaScript for checkboxes?

JavaScript allows us to dynamically set the number of HTML checkboxes. This is useful for:

  • Form validation
  • User interactions
  • Conditional display of elements

Since you are here, you are surely facing issues with either single checkboxes (individual) or multiple checkboxes (grouped). In the first part, we will discuss single checkbox manipulation using JS, and then we will also explain how you can work with the check and uncheck states of grouped checkboxes.

Basic HTML Checkbox

Here is the basic HTML for a checkbox:

<input type="checkbox" id="myCheckbox">
<label for="myCheckbox">Check me!</label>

Note

To make a checkbox checked by default, just add the checked attribute in your HTML code.

Checking a Single Checkbox with JavaScript

To check a checkbox using JavaScript, you need to set the checked property from false to true.

Code Example

<input type="checkbox" id="myCheckbox">
<button onclick="checkCheckbox()">Check</button>

<script>
  function checkCheckbox() {
    document.getElementById('myCheckbox').checked = true;
  }
</script>

In this example, clicking the “Check” button will check the checkbox.

Note

If we submit an unchecked checkbox, then the name and value is not submitted to the server.

Unchecking a Single Checkbox with JavaScript

To uncheck a checkbox using JavaScript, you need to set the checked property from true to false.

Code Example

<input type="checkbox" id="myCheckbox">
<button onclick="uncheckCheckbox()">Uncheck</button>

<script>
  function uncheckCheckbox() {
    document.getElementById('myCheckbox').checked = false;
  }
</script>

In this example, clicking the “Uncheck” button will uncheck the checkbox.

JavaScript Check and Uncheck Checkbox: Toggle Single Checkbox State

Sometimes, you may want to toggle the state of a checkbox. This means checking it if it’s unchecked and unchecking it if it’s in checked state.

buymeacoffee

Code Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Check and Uncheck Checkbox: Toggle Single Checkbox</title>
</head>

<body>
    <input type="checkbox" id="myCheckbox"><br><br>
    <button onclick="toggleCheckbox()">Toggle</button>
</body>

<script>
    function toggleCheckbox() {
    var checkbox = document.getElementById('myCheckbox');
    checkbox.checked = !checkbox.checked;
    }
</script>
JavaScript Check and Uncheck Checkbox – Toggle a checkbox

In this example, clicking the “Toggle” button will toggle the checkbox state.

JavaScript Check and Uncheck Checkbox: Checking Multiple Checkboxes

Sometimes you may need to check or uncheck multiple checkboxes at a time. You can do this by looping through a list of checkboxes. If your checkbox list has a name, then you can do it by name, or else do it by class name.

Check Uncheck Checkboxes by Name

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Check and Uncheck Checkbox by Name</title>
</head>

<body>
    <input type="checkbox" id="checkbox1" name="courses"><label>JavaScript</label>
    <input type="checkbox" id="checkbox2" name="courses"><label>HTML</label>
    <input type="checkbox" id="checkbox3" name="courses"><label>CSS</label>
    <br><br>
    <button onclick="checkAll()">Check All</button>
    <button onclick="uncheckAll()">Uncheck All</button>
</body>
</html>

<script>
    function checkAll() {
      var checkboxes = document.getElementsByName('courses');
      checkboxes.forEach(checkbox => checkbox.checked = true);
    }
  
    function uncheckAll() {
      var checkboxes = document.getElementsByName('courses');
      checkboxes.forEach(checkbox => checkbox.checked = false);
    }
</script>

Output

JavaScript Check and Uncheck Checkbox – by name

In this example, clicking the “Check All” button will check all checkboxes, and clicking the “Uncheck All” button will uncheck all checkboxes.

Check Uncheck Checkboxes by Class Name

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Check and Uncheck Checkbox by Class Name</title>
</head>

<body>
    <input type="checkbox" id="checkbox1" class="groupedCHK" ><label>JavaScript</label>
    <input type="checkbox" id="checkbox2" class="groupedCHK"><label>HTML</label>
    <input type="checkbox" id="checkbox3" class="groupedCHK"><label>CSS</label>
    <br><br>
    <button onclick="checkAll()">Check All</button>
    <button onclick="uncheckAll()">Uncheck All</button>
</body>
</html>

<script>
    function checkAll() {
      var checkboxes = document.querySelectorAll('.groupedCHK');
      checkboxes.forEach(checkbox => checkbox.checked = true);
    }
  
    function uncheckAll() {
      var checkboxes = document.querySelectorAll('.groupedCHK');
      checkboxes.forEach(checkbox => checkbox.checked = false);
    }
</script>

As we are following the the same HTML code thus the output also same like the previous one.

JS Check Checkbox Based on Condition

<script>
    function checkAll() {
      var checkboxes = document.querySelectorAll('.groupedCHK');
      checkboxes.forEach(checkbox => {if(checkbox.id=='checkbox2')checkbox.checked = true});
    }
  
    function uncheckAll() {
      var checkboxes = document.querySelectorAll('.groupedCHK');
      checkboxes.forEach(checkbox => checkbox.checked = false);
    }
</script>

Output: JS Check Checkbox

JS check checkbox based on condition
buymeacoffee

Table of Common Methods

TaskMethod
Check a checkboxdocument.getElementById('myCheckbox').checked = true;
Uncheck a checkboxdocument.getElementById('myCheckbox').checked = false;
Toggle checkbox statecheckbox.checked = !checkbox.checked;
Check multiple checkboxescheckboxes.forEach(checkbox => checkbox.checked = true);
Uncheck multiple checkboxescheckboxes.forEach(checkbox => checkbox.checked = false);
Check based on conditionif (condition) { checkbox.checked = true; }
JS Check Checkbox Methods

Advanced Techniques

Using Event Listeners

You can also use event listeners to manage checkbox states.

<input type="checkbox" id="myCheckbox">
<button id="toggleButton">Toggle</button>

<script>
  document.getElementById('toggleButton').addEventListener('click', function() {
    var checkbox = document.getElementById('myCheckbox');
    checkbox.checked = !checkbox.checked;
  });
</script>

In this example, clicking the “Toggle” button will toggle the checkbox state using an event listener.

Handling Checkbox Change Events

If you need to perform an action when a checkbox state changes. Then follow the below example:

<input type="checkbox" id="myCheckbox">

<script>
  document.getElementById('myCheckbox').addEventListener('change', function() {
    if (this.checked) {
      console.log('Checkbox is checked');
    } else {
      console.log('Checkbox is unchecked');
    }
  });
</script>

Output Based on User Click

JavaScript Check and Uncheck Checkbox based on user click
JavaScript Check and Uncheck Checkbox based on user click

In this example, a message will be logged to the console whenever a user clicks on the checkbox to change its state.

Conclusion

Mastering the JavaScript check and uncheck checkbox helped us build an interactive web application. Whether you need to manage a single checkbox or multiple checkboxes, JavaScript provides useful methods to handle checkboxes check states efficiently. Use the examples provided in this article to implement dynamic checkbox functionality in your projects. This will make your web pages more responsive and user-friendly.

Shawpnendu Bikash Maloroy
Shawpnendu Bikash Maloroy

๐Ÿ‹๏ธโ€โ™‚๏ธ Discover Code Blocks From 20+ yrs JS Expert
๐Ÿ’ฅ Asp.net C# Developer
๐Ÿ† Solution Architect
๐Ÿ‘จโ€โœˆ๏ธ Database Administrator
๐Ÿ“ข Speaker
๐ŸŽ“ MCTS since 2009

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Spread the love
ยซPrevious
Nextยป

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • 5 Lesser-Known JavaScript Functions
    5 Lesser-Known JavaScript Functions to Boost Your Coding Efficiency
  • 7 Weird JavaScript Tricks That Look Like Bugs
    7 Weird JavaScript Tricks That Look Like Bugs (#3 Will Shock You!)
  • Build a JavaScript Gamer Journal in 8 Lines
    ๐ŸŽฎ Build a JavaScript Gamer Journal in 8 Lines: Track Your Wins Like a Pro! ๐Ÿ†
  • JavaScript Pet Feeder Reminder in 7 Lines
    How to Code a Simple JavaScript Pet Feeder Reminder in 7 Lines: Feed Your Pet Like a Coding Boss! ๐Ÿถ
  • 10-line calculator JavaScript
    Build a Simple Calculator in JavaScript: 10 Lines to Wow Your Friends!

About-CodersTech Zone |  Contact |  Disclaimer |  Fact-Checking policy |  Affiliate Disclosure |  Privacy Policy

Copyright ยฉ 2024 CodersTechZone.com