yellowSub
yellowSub

Reputation: 209

How to uncheck checkboxes on a button click?

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;
  }
}

Upvotes: 1

Views: 4199

Answers (2)

AVJT82
AVJT82

Reputation: 73337

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

Upvotes: 3

Nimitt Shah
Nimitt Shah

Reputation: 4587

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 (===)!

Upvotes: 4

Related Questions