如何在按钮单击时获得多个复选框值? [英] How to get multiple checkbox value on button click?

查看:123
本文介绍了如何在按钮单击时获得多个复选框值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是带有复选框的汽车ID列表。

this is list of cars id with checkbox.

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

点击此按钮点击我想获取我的.ts文件中所有汽车的价值。
这里的函数是.ts

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


推荐答案

为了获得价值选中了多个复选框,无需使用上述答案中给出的DOM选择器,您可以采用角度方式执行此操作。

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.

为了获取复选框的所有值,有几个Angular中提供了各种方法。在这个答案中,我将告诉你不使用任何formArray。像这样 -

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

这篇关于如何在按钮单击时获得多个复选框值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆