Check/Uncheck Checkbox with JavaScript

How to Check/Uncheck Checkbox with JavaScript

How to Check/Uncheck Checkbox with JavaScript

This article will demonstrate how to use JavaScript to check and uncheck checkboxes. It saves the user time and facilitates checking and unchecking the checkbox.

 

 Check/Uncheck Checkbox with JavaScript

We will learn more about checkboxes before we begin our project on utilising Javascript to check and uncheck checkboxes.

What is a CheckBox?

HTML’s input tag has a checkbox as one of its attributes. On the front end, they appear as square boxes that can be dynamically checked. When we want to request a variety of input from the user, the HTML checkbox comes in quite handy. When asked a question with a checkbox, users choose from the whole list of possibilities by checking or ticking the appropriate text boxes.

What is the use of CheckBox?

Checkboxes are used when there are lists of possibilities and the user can select zero, one, or a number of options. In other words, clicking one box does not uncheck the others because each checkbox exists independently of every other checkbox in the list.

Step1: HTML For Checkbox

main
  h1 Programatically check and <br />uncheck checkboxes with <br />vanilla JS
  p See the&nbsp;
    a(
      href="https://aileenrae.co.uk/blog/programatically-check-uncheck-checkbox-javascript"
    ) blog post
    | &nbsp;for further reading.
  section#incorrect
    h2 ❌ <code>element.setAttribute("checked", value)</code>
    form
      input#incorrect-select-all(type="checkbox")
      label(for="incorrect-select-all") Select All
      - var n = 1;
        while n < 4
          .child
            input.incorrect-child-checkbox(
              id='incorrect-child-' + n,
              type="checkbox"
            )
            label(for='incorrect-child-' + n) Child #{n++}
  section#correct
    h2 ✅ <code>element.checked = value</code>
    form
      input#correct-select-all(type="checkbox")
      label(for="correct-select-all") Select All
      - var n = 1;
        while n < 4
          .child
            input.correct-child-checkbox(id='correct-child-' + n, type="checkbox")
            label(for='correct-child-' + n) Child #{n++}

We will now build the structure for our checkbox using the main tag. First, we’ll use the h1 tag inside the main tag to provide the heading for our check and uncheck boxes. Next, we’ll use the form tag to construct numerous checkboxes inside it using the input type “checkbox.”

Checkboxes of two different sorts will be made, one utilising the set. The element.checked property works with attribute and other. We will design the checkbox structures because using javascript, we can add and remove checkboxes by utilising these two techniques.

Let’s now examine the structure of our HTML.

HTML Output:

 Check/Uncheck Checkbox with JavaScript

Step2: CSS (Cascading Style Sheet)

$bp: 700px;

*,
*::before,
*::after {
  box-sizing: border-box;
}

html {
  height: 100%;
}

body,
main {
  min-height: 100%;
}

body {
  background-color: ghostwhite;
}

main {
  background-color: white;
  display: flex;
  font-family: monospace;
  flex-direction: column;
  margin: 0 auto;
  max-width: 500px;
  padding: 50px 15px;
}

h1 {
  text-align: center;
}

section {
  width: 100%;

  h2 {
    font-size: 1.1rem;
  }
}

form {
  padding: 0 34px;
}

label {
  font-size: 1rem;
}

input[type="checkbox"] {
  height: 15px;
  width: 15px;
}

.child {
  margin-top: 10px;
  padding-left: 24px;
}

Step1:We will begin by adding some fundamental default styling to our website. Using the universal tag selector (*), we will set the box sizing to “border-box,” and then using the html tag selector, we will set the height to “100%” of the body of our webpage. We’ll set the background to “ghost white” by using the background colour parameter as well.

$bp: 700px;

*,
*::before,
*::after {
  box-sizing: border-box;
}

html {
  height: 100%;
}

body,
main {
  min-height: 100%;
}

body {
  background-color: ghostwhite;
}

Step2:Now, using the class selector (.main), we will change the background to “white” using the background colour property, and we will set the display to “flex” using the display property. We will also set the font family property to “monospace” using this method. The maximum width will be 500 pixels according to the maximum width property.

main {
  background-color: white;
  display: flex;
  font-family: monospace;
  flex-direction: column;
  margin: 0 auto;
  max-width: 500px;
  padding: 50px 15px;
}

h1 {
  text-align: center;
}

Step3:We shall now style our form. The padding is set to 0 pixels and 34 pixels, accordingly. We will use the label property to set the label to 1 rem and the input type selector to set the width and height to 15 px.

We’ll now change the top margin to 10 px and the left padding to 20 px, respectively, using the class selector (.child).

label {
  font-size: 1rem;
}

input[type="checkbox"] {
  height: 15px;
  width: 15px;
}

.child {
  margin-top: 10px;
  padding-left: 24px;
}

CSS Output:

 Check/Uncheck Checkbox with JavaScript

 

Step2: Javascript for Check and Uncheck checkboxes

// ❌ Using setAttribute
(() => {
  const selectAllCheckbox = document.getElementById("incorrect-select-all");
  const childCheckboxes = document.querySelectorAll(
    ".incorrect-child-checkbox"
  );

  const toggleSelectAllCheckbox = () => {
    const areAllChecked = [...childCheckboxes].every((c) =>
      c.hasAttribute("checked")
    );
    if (areAllChecked) {
      // uncheck all if every checkbox is checked
      childCheckboxes.forEach((c) => {
        c.removeAttribute("checked");
      });
    } else {
      // otherwise, check all
      childCheckboxes.forEach((c) => {
        c.setAttribute("checked", "");
      });
    }
  };

  selectAllCheckbox.addEventListener("click", toggleSelectAllCheckbox);
})();

// ✅ Setting checked property
(() => {
  const selectAllCheckbox = document.getElementById("correct-select-all");
  const childCheckboxes = document.querySelectorAll(".correct-child-checkbox");

  const toggleSelectAllCheckbox = () => {
    const areAllChecked = [...childCheckboxes].every((c) => c.checked === true);
    childCheckboxes.forEach((c) => {
      c.checked = !areAllChecked;
    });
    selectAllCheckbox.checked = !areAllChecked;
  };

  selectAllCheckbox.addEventListener("click", toggleSelectAllCheckbox);

  // Handle child click events
  const toggleChildCheckbox = () => {
    const areAllChecked = [...childCheckboxes].every((c) => c.checked === true);
    selectAllCheckbox.checked = areAllChecked;
  };

  childCheckboxes.forEach((c) => {
    c.addEventListener("click", toggleChildCheckbox);
  });
})();

We’ll make an anonymous function in javascript and use the document inside of it. document.queryselector and getElementById Using the if and else method, we will select all of the HTML components in the all method. The checkboxes will be examined to see if they are checked or not; if checked, they will become unchecked, and vice versa.

 Final Output Of Check/Uncheck Checkbox:

Live Preview:

Now We have Successfully created our javascript using checkbox uncheck. You can use this project for your personal webpage and We hope you understood the project, If you any doubt feel free to comment!! If you find out this Blog helpful, then make sure to search Codewithrandom on Google for Front End Projects with Source codes and make sure to Follow the Code with Random Instagram page.

Written By : @arun
Code by : @Aileen Rae


Leave a Reply