只选中一个复选框 [英] Select only one check box

查看:107
本文介绍了只选中一个复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用离子2和角度2进行小型项目。我希望用户只能从提供的复选框中选择一个复选框。每当选中一个复选框但我不确定该函数应该执行什么时,我添加了动作监听器。

I am using ionic 2 and angular 2 for a small project. and I want the user to be able to only select one checkbox from the ones provided. I added and action listener whenever a checkbox is checked but not sure on what the function should really execute.

    <ion-item *ngFor="let category of categories; let i = index">
      <ion-label [innerHTML]="category.name"></ion-label>
      <ion-checkbox color="royal" checked="category.value" (click)="Selection(i,categories);"></ion-checkbox>
  </ion-item>

以下是JSON对象的示例

Here is the sample of the JSON object

    categories = [
    {
      name: 'Car Keys',
      value: 'false'
  },
  {
      name: 'Phone',
      value: 'false'
  },
  {
      name: 'ID/Drivers License',
      value: 'false'
  },
  {   name: 'Wallet',
      value: 'false'
  },
  {   name: 'Other',
      value: 'false'
  }]

我将类别的索引传递给函数但不确定还有什么要检查。任何帮助将不胜感激。

I am passing the index of the categories into the function but not sure what else to check for. Any help would be appreciated.

推荐答案

这可以通过单选按钮最简单地实现,但如果你想使用复选框,这将是意味着你应该在选择一个复选框时禁用其他复选框。

This could easiest be achieved using radio buttons, but if you want to use checkboxes, this would mean you should disable the other checkboxes when one is chosen.

你拥有的数组,将属性更改为相反,我们可以使用布尔值 false 。然后当选中一个复选框时,它会调用你的 Selection -function,它将其他复选框的值设置为 true 当选择一个时,保持选择为假。当用户取消选中复选框时,所有复选框值再次为 false 。为此我们使用唯一的name属性,该属性被传递给函数,当我们迭代类别以查看哪个被检查时。所以你的功能:

The array you have, change the value property to a boolean value false instead, which we can work with. Then when a checkbox is chosen, it would invoke your Selection-function, which sets the other checkboxes' value to to true when one is chosen, keeping the one chosen as false. When user unchecks checkbox, all checkboxes values are again false. To this we use the unique name property, which is passed to the function and when we iterate the categories to see which one is checked. So your function:

Selection(name: string) {
   this.categories.forEach(x => {
       if(x.name !== name) {
           x.value = !x.value
       }
   })
}

在您的模板中添加禁用选项:

And to your template, add the disabled option:

<ion-item *ngFor="let category of categories; let i = index">
  <ion-label>{{category.name}}</ion-label>
  <ion-checkbox [disabled]="categories[i].value" (click)="Selection(category.name);"></ion-checkbox>
</ion-item>

这篇关于只选中一个复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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