kalememre
kalememre

Reputation: 426

How can I get all values from multiple checkboxes in Ionic

I have an app and for this page I use checkbox. And I want to pick up from users more options. When I click the button, I want to see all checked options.

My .html codes

 <ion-item *ngFor="let item of durumozellikleri">
        <ion-label>{{item.ozellik}}</ion-label>
        <ion-checkbox [(ngModel)]="durumozellik"></ion-checkbox>
 </ion-item>

 <button ion-button (click)="getAll()">Click Me</button>

My .ts codes

 let headers: any = new HttpHeaders({ 'Content-Type':'application/json' }),
 options: any = { "key": "kontrol", "id": this.id},
 url: any = 'http://207.180.202.55/MisKebap/php/durumozellikgetir.php';


 this.http.post(url, JSON.stringify(options), headers)
 .map(res => res.json())
 .subscribe(res => {

   this.durumozellikleri = res;
 })

Upvotes: 1

Views: 1732

Answers (2)

wentjun
wentjun

Reputation: 42516

You can try making the following changes on both your component.ts, and component.html.

On your component.html, you have to bind the checked values of each element in the durumozellikleri array to the ngModel.

<ion-item *ngFor="let item of durumozellikleri">
  <ion-label>{{item.ozellik}}</ion-label>
  <ion-checkbox [(ngModel)]="item.checked"></ion-checkbox>
</ion-item>

<button ion-button (click)="getAll()">Click Me</button>

And on your component.ts, I am not sure the exact structure of durumozellikleri, but you should add an additional property called checked in each object within durumozellikleri. And to get only the checked options, you can use Array.filter().

this.durumozellikleri=[
  {ozellik : '123', checked : false},
  {ozellik : '234', checked : false},
  {ozellik : '214', checked : false},
];

getAll() {
  console.log(this.durumozellikleri);
  const res = this.durumozellikleri.filter(obj => obj.checked);
  console.log(res)
  // do the rest here
}

Here is a working demo.

Upvotes: 1

ysf
ysf

Reputation: 4844

you can add a field to items in durumozellikleri and use that field to store the checkbox value as follows;

  durumozellikleri = [
    { ozellik: "ozellik1", secim: false },
    { ozellik: "ozellik2", secim: false },
    { ozellik: "ozellik3", secim: false },
  ]

in html

<ion-item *ngFor="let item of durumozellikleri">
    <ion-label>{{item.ozellik}}</ion-label>
    <ion-checkbox [(ngModel)]="item.secim"></ion-checkbox>
 </ion-item>

here is a simple demo https://stackblitz.com/edit/angular-u6ecgk

Upvotes: 0

Related Questions