使用复选框作为单选按钮

时间:2010-04-16 05:53:34

标签: javascript html ajax

我正在寻找一种方法让用户选择两个选项中的一个(强度或弱点)来获得质量列表。

例如:

                   strength     weakness  not applicable
1. Communication 
2. Punctuality
   ...

单选按钮让我选择强度或弱点。但是,我希望用户只检查那些适用的质量,如果用户意外选择了质量,则无法撤消单选按钮的选择,除非有第三个不适用的单选按钮或让用户重新输入这页纸。我想知道是否有办法能够获得复选框的灵活性(选中/取消选中),除了在选中或取消选中其中一个而不是使用三个单选按钮时禁用或启用另一个复选框。

我不认为我之前已经看过这种行为,所以想知道是否有更优雅的方式来做这件事。我愿意接受其他想法以获得相同的功能。使用复选框作为单选按钮只是一个想法。

非常感谢。

3 个答案:

答案 0 :(得分:14)

基于javascript的解决方案

function SetSel(elem)
{
  var elems = document.getElementsByTagName("input");
  var currentState = elem.checked;
  var elemsLength = elems.length;

  for(i=0; i<elemsLength; i++)
  {
    if(elems[i].type === "checkbox")
    {
       elems[i].checked = false;   
    }
  }

  elem.checked = currentState;
}​

<input type="checkbox" class="chkclass" onclick="SetSel(this);" />
<input type="checkbox" class="chkclass" onclick="SetSel(this);" />
<input type="checkbox" class="chkclass" onclick="SetSel(this);" />
<input type="checkbox" class="chkclass" onclick="SetSel(this);" />

<强> Working Demo

基于jQuery的解决方案

$(function(){
    $("input:checkbox.chkclass").click(function(){
      $("input:checkbox.chkclass").not($(this)).removeAttr("checked");
      $(this).attr("checked", $(this).attr("checked"));    
    });
});​

<input type="checkbox" class="chkclass" />
<input type="checkbox" class="chkclass" />
<input type="checkbox" class="chkclass" />
<input type="checkbox" class="chkclass" />

<强> Working Demo

答案 1 :(得分:5)

你不应该使用复选框作为单选按钮(反之亦然):这与用户的心理模型不一致,因此会让人感到困惑。

这是一个没有理想解决方案的问题,但您最初建议将“不适用”选项作为一组3个单选按钮的一部分是相当普遍的。如果您在默认情况下预先选择“不适用”选项并且可能在视觉上不加重显示(例如,将其灰显),那么从用户的角度来看,它几乎就像只有2个选项,但是它们如果他们不小心选择了一个并且想要“取消选择”它,就可以恢复。

答案 2 :(得分:4)

这是正确的形式,“已检查”是专有而非属性

   $(function(){
      $("input:checkbox.chkclass").each(function(){
        $(this).change(function(){
            $("input:checkbox.chkclass").not($(this)).prop("checked",false);
            $(this).prop("checked", $(this).prop("checked"));       
        });   
      });
    });
相关问题