1

I have the following 3 input checkboxes, after checking the checkboxes, I would like to clear all the checked items after the "Clear Checkbox" button is clicked. I attempted the following but it doesn't work.

Stackblitz working Example

app.component.html

<ul *ngFor="let d of data">
  <li>
    <input id="checkbox" type="checkbox" class="checkbox" />
    {{ d }}
  </li>
</ul>

<button (click)="myFunction()">Clear Checkbox</button>

app.component.ts

export class AppComponent {
  data = ['tea', 'coffe', 'soda'];
  public myFunction() {
    (<HTMLInputElement>document.getElementById('checkbox')).checked === false;
  }
}
4
  • Try <HTMLInputElement>document.getElementById('checkbox')).checked = false, With ===, you are making a comparison. Commented Nov 12, 2021 at 17:30
  • @T.Trassoudaine my bad, now it works but only changes value to one item Commented Nov 12, 2021 at 17:32
  • 1
    Yes because you are selecting by id, you can't have several HTML elements with same id, use class instead. Nimitt Shah answer gives details. Commented Nov 12, 2021 at 17:34
  • You should really investigate the Angular Way of doing this. This implementation will cause you headaches eventually.. Commented Nov 12, 2021 at 17:43

2 Answers 2

4

You can use document.querySelectorAll() to uncheck all the checkboxes.

StakBlitz Working Example

In myFunction, you code should be as below:

document.querySelectorAll('.checkbox').forEach(_checkbox=>{
    (<HTMLInputElement>_checkbox).checked = false;
});

Also, make sure you are assinging false value (=) not checking (===)!

Sign up to request clarification or add additional context in comments.

3 Comments

You still should make sure the id of the checkboxes are not all the same.
yea, I am not using id
In the question and in your StackBlitz example, all the checkboxes have the id checkbox.
3

I would do it in an angular fashion and use ViewChildren instead. So attach a ref to your checkboxes and access them with ViewChildren, as this would be a perfect case for that. So I attached chkboxes to the input

<input #chkboxes id="checkbox" type="checkbox" class="checkbox" />

I define the querylist:

@ViewChildren('chkboxes') chkboxes: QueryList<ElementRef>;

and to uncheck I loop the elements and set them to false:

myFunction() {
  this.chkboxes.forEach(x => x.nativeElement.checked = false)
}

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.