0

I'm working on an app and one of the pages requires the user to choose payment by credit/card or cash. I want to make it so that both check boxes cannot be checked at the same time (If one is checked the other is unchecked).

I have tried making an event with ionChange so that if one of them is checked the boolean value of the other checkboxes becomes false.

HTML

 <ion-item>
    <ion-label>Credit/Debit Card (N/A)</ion-label>   
    <ion-checkbox item-start [(ngModel)]='CC' (ionChange)="checked()"></ion-checkbox>
  </ion-item>
  <br/><br/>

  <ion-item>
    <ion-label>Cash</ion-label>
    <ion-checkbox item-start [(ngModel)]='Cash' (ionChange)="checked()"></ion-checkbox>
  </ion-item>

Typescript

 Cash = false;    
  CC = false;      

  checked(){
    if(this.Cash == true){
      this.CC = false;
    }

    if(this.CC == true){
      this.Cash = false
    }
  }

I expected this to work but it is still possible to check both boxes.

Qassim Ali
  • 57
  • 7

1 Answers1

1

The best way to solve this is to use Radio-button instead of Checkbox .but if you want to do it by checkbox than the code is at follow:-

HTML

 <input type="checkbox" name="1" [(ngModel)]="check1"
 (change)="onchange($event)"/>
 {{check1}}


 <input type="checkbox" name="2" [(ngModel)]="check2"
  (change)="onchange1($event)"/>
 {{check2}}

TypeScript

export class AppComponent {

  check1: boolean;
  check2: boolean;

  onchange(event: any) {
    if (this.check1 == !event.target.checked) {
      this.check2 = true;
    }
    else {
      this.check2 = false;
    }
  }

  onchange1(event: any) {
    if (this.check2 == !event.target.checked) {
      this.check1 = true;
    }
    else {
      this.check1 = false;
    }
  }
}

hope its work fine for you.

m_s
  • 11
  • 2
  • This is a very specific answer which will only work for two checkboxes, using a group is better approach.Check out the link I had shared above – Hargun Singh Jul 23 '19 at 12:49