【问题标题】:To select only one checkbox at a time and execute a particular task on a particular checkbox being selected or both of the checkboxes being unchecked一次只选择一个复选框,并在选中的特定复选框或未选中的两个复选框上执行特定任务
【发布时间】:2019-09-02 03:23:00
【问题描述】:

我有两个复选框,目标是一次只允许选择一个复选框 根据对特定复选框的选择或两个复选框都未选中的情况,需要执行更多不同的任务。 我已经实现了这一点,并且在选中其中一个复选框或未选中两个复选框时执行任务时遇到问题

<div *ngFor="let chk of checkboxes">
<input type="checkbox" [checked]="chk.checked" 
(click)="uncheckOther(chk)"> {{chk.value}}
</div>

TS 代码:

  checkboxes = [{ checked: false, value: 'Request' }, { checked: false, 
  value: 'Reservation' }];    

  uncheckOther(chk) {
   //uncheck all
   this.checkboxes.forEach(x => {
   if(x.checked == true)
   x.checked = false;
  })

  //check the selected
   if(chk.checked == true) {
   chk.checked = false; 
    } else {
   chk.checked = true;
   }
//Execute task if any one of the checkboxes are selected
   if(chk.value === "Request" && chk.checked == true){
    console.log("call request data")
   } else if(chk.value === "Reservation" && chk.checked == true){
    console.log("call Reservation data");
   }
//Execute task if none of them is checked
   this.checkboxes.forEach(x => {
   if(x.checked === false)
   console.log("call both combined data")
   })
   }

一次只能选择一个复选框,并且需要执行一些任务,具体取决于选中的复选框或两个复选框都未选中,这也是默认情况(或可能被用户取消选中)

【问题讨论】:

  • 需要更多解释
  • 什么不起作用?
  • 所以默认情况下,当页面加载时,复选框将被取消选中,我们将合并数据(请求+预订),当用户点击请求(复选框)时,请求数据将可用,第二种情况用户点击on Reservation(Checkbox) 保留数据将可用,第三种情况现在任何一个复选框都被选中,例如:Request(Checkbox) 和用户取消选中 Request(Checkbox) 然后两个组合数据都应该可用。
  • 所以我在获取正确的复选框相关数据(执行任务注释代码)时遇到问题。其中一个被选中或两个都未被选中
  • 不,那是我写的,只有一个复选框应该被允许被选中,它正在工作,但是执行任务的东西不起作用。

标签: angular typescript checkbox


【解决方案1】:

需要一些改动:

HTML 代码:

<div *ngFor="let chk of checkboxes">
  <input type="checkbox" [(ngModel)]="chk.checked" (ngModelChange)="uncheckOther(chk,$event)"> 
  {{chk.value}}
</div>

TS 代码:

uncheckOther(chk, event) {

  if (event) {
    //uncheck all
    this.checkboxes.forEach(x => {
      if (x.checked == true)
        x.checked = false;
    })
    //check the selected
    if (chk.checked == true) {
      chk.checked = false;
    } else {
      chk.checked = true;
    }
    if (chk.value == "Request") {
      console.log('Call Request API')
    }
    else if (chk.value == "Reservation") {
      console.log('Call Reservation API')
    }
  }
  else {
    console.log('Call Both API')
  }
}

Working Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    • 2017-08-10
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多