How to get multiple checkbox value on button click

2019-03-03 10:18发布

问题:

<td><p><input  class="checkbox"  type="checkbox" value="Cars.id"> </p> </td> 

this is list of cars id with checkbox.

     <button (click)="duplicate()" ><ion-icon  name="color-wand"></ion-icon> </button> 

on this button click i want to get value of all cars in my .ts file. here is the function in .ts

duplicate(){
    var checkedValue = document.querySelector('.messageCheckbox:checked');
}

回答1:

In order to get values of selected multiple checkboxes, No need to use DOM selectors as given in above answers you can do this in angular way.

In order to get all values of checkbox, there are several ways are available in Angular. In this answer I'll show you without using any formArray. like this -

<div *ngFor="let Car of Cars">
      <input type="checkbox" (change)="onChange(Car.id, $event.target.checked)"> {{Car.email}}<br>
  </div>

<button (click)="duplicate()" >Get values </button> 
 ----------------------------
emailFormArray: Array<any> = [];
  Cars = [ 
    {email:"email1", id: 1},
    {email:"email2", id: 2},
    {email:"email3", id: 3},
    {email:"email4", id: 4}
  ];

  onChange(email:string, isChecked: boolean) {
      if(isChecked) {
        this.emailFormArray.push(email);
      } else {
        let index = this.emailFormArray.indexOf(email);
        this.emailFormArray.splice(index,1);
      }
  }

  duplicate() {
    console.log(this.emailFormArray);
  }

Working Example



回答2:

First make sure you do not duplicated ids.

You can use document.querySelector() to query the dom and get the values.

<td> <p>  <input id="checkbox1" class="messageCheckbox" type="checkbox" value="Audi"> </p> /td>
<td> <p>  <input id="checkbox2" class="messageCheckbox" type="checkbox" value="BMW"> </p> /td>
<td> <p>  <input id="checkbox3" class="messageCheckbox" type="checkbox" value="Tesla"> </p> /td>

var checkedValue = document.querySelector('.messageCheckbox:checked').value;

In Angular you could try to use the directive input[checkbox] more info here:

https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D