Home > database >  How to uncheck checkboxes on a button click?
How to uncheck checkboxes on a button click?

Time:11-13

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

CodePudding user response:

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

CodePudding user response:

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

  • Related