选中另一个复选框时,自动取消选中复选框

时间:2017-02-20 10:34:18

标签: checkbox xul

我使用XUL,我有两个hbox,每个都有一个复选框:

<hbox id="hBox1">
   <label value="label1" style="width:15ex" />
   <spacer style="width:5px" />
   <checkbox id="checkBox1" style="width: 2ex" />
</hbox>

<hbox id="hBox2">
   <label value="label2" style="width:15ex" />
   <spacer style="width:5px" />
   <checkbox id="checkBox2" style="width: 2ex" />
</hbox>

我想有这样的行为:只能检查两个chekbox中的一个,即如果用户选中一个复选框而另一个选中,则必须自动取消选中第二个复选框

我试过了:

<checkbox id="checkBox1" style="width: 2ex" onchange="if (this.checked) document.getElementById('checkBox2').checked = false" />

<checkbox id="checkBox2" style="width: 2ex" onchange="if (this.checked) document.getElementById('checkBox1').checked = false" />

但它不起作用

1 个答案:

答案 0 :(得分:0)

当您使用onchange时,您正在使用concommand

以下作品:

<hbox id="hBox1">
   <label value="label1" style="width:15ex" />
   <spacer style="width:5px" />
   <checkbox id="checkBox1" style="width: 2ex" oncommand="if (this.checked) document.getElementById('checkBox2').checked = false" />
</hbox>

<hbox id="hBox2">
   <label value="label2" style="width:15ex" />
   <spacer style="width:5px" />
   <checkbox id="checkBox2" style="width: 2ex" oncommand="if (this.checked) document.getElementById('checkBox1').checked = false" />
</hbox>

但是,这会导致复选框标签实际上与复选框无关(单击标签不会选中/取消选中复选框)以及<checkbox> label通常会出现的小图形工件显示。通常,左侧的标签将使用dir属性实现:

<hbox id="hBox1">
  <vbox id="vBox1">
   <checkbox id="checkBox1" dir="reverse" label="label1" style="width: 21ex" oncommand="if (this.checked) document.getElementById('checkBox2').checked = false" />
   <checkbox id="checkBox2" dir="reverse" label="label2" style="width: 21ex" oncommand="if (this.checked) document.getElementById('checkBox1').checked = false" />
  </vbox>
</hbox>

<radio>按钮专门用于允许单个选择

这通常在<radio>内使用<radiogroup>来实现。放置在<radio>内时,<radiogroup>框会自动出现此行为。它们的风格通常有点不同(圆形,而不是方形),但如果您愿意,可以使用CSS进行更改。但是,圆形样式旨在向用户提供它是单选按钮的信息并具有此行为。

<hbox>
  <vbox>
    <radiogroup>
      <radio id="checkBox1" dir="reverse" label="label1" style="width: 21ex" />
      <radio id="checkBox2" dir="reverse" label="label2" style="width: 21ex" />
    </radiogroup>
  </vbox>
</hbox>