简体   繁体   English

如何使一组复选框互斥?

[英]How can I make a group of checkboxes mutually exclusive?

I have to make mutually exculsive checkboxes. 我必须制作相互冲动的复选框。 I have come across numerous examples that do it giving example of one checkbox group. 我遇到过很多例子,它给出了一个复选框组的例子。 One example is at http://blog.schuager.com/2008/09/mutually-exclusive-checkboxes-with.html . 一个例子是http://blog.schuager.com/2008/09/mutually-exclusive-checkboxes-with.html

In my case, I have many checkbox groups on the same page, so I want it to work like this example . 在我的情况下,我在同一页面上有许多复选框组,所以我希望它像这个例子一样工作。 An asp.net codebehind example is here , but I want to do it in client side code. 这里有一个asp.net代码隐藏示例 ,但我想在客户端代码中执行此操作。

How can I do this in JavaScript? 我怎样才能在JavaScript中执行此操作?

i have decided to use the ajax mutually exclusive checkbox extender. 我决定使用ajax互斥复选框扩展器。 The solutions given so far are basically based on radio buttons. 到目前为止给出的解决方案基本上是基于单选按钮。 This link really helped me.. http://www.asp.net/ajax/videos/how-do-i-use-the-aspnet-ajax-mutuallyexclusive-checkbox-extender 这个链接真的帮了我.. http://www.asp.net/ajax/videos/how-do-i-use-the-aspnet-ajax-mutuallyexclusive-checkbox-extender

Using Mutual Checkboxes when there is Radio button is a bad idea but still you can do this as follows 当有单选按钮时使用Mutual Checkbox是一个坏主意但仍然可以按如下方式执行此操作

HTML HTML

<div>    
    Red: <input id="chkRed" name="chkRed" type="checkbox" value="red" class="checkbox">
    Blue: <input id="chkBlue" name="chkBlue" type="checkbox" value="blue" class="checkbox">
    Green: <input id="chkGreen" name="chkGreen" type="checkbox" value="green" class="checkbox">
</div>

<div>
    Mango: <input id="chkRed" name="chkMango" type="checkbox" value="Mango" class="checkbox">
    Orange: <input id="chkBlue" name="chkOrange" type="checkbox" value="Orange" class="checkbox">
    Banana: <input id="chkGreen" name="chkBanana" type="checkbox" value="Banana" class="checkbox">
</div>

Jquery jQuery的

$('div .checkbox').click(function () { 
                 checkedState = $(this).attr('checked');
                  $(this).parent('div').children('.checkbox:checked').each(function () {
                      $(this).attr('checked', false);
                  });
                  $(this).attr('checked', checkedState);
});

And here is fiddle 这里是小提琴

Like I said in my comment, you should really use <radio> elements for this. 就像我在评论中说的那样,你应该真正使用<radio>元素。 Give them the same name and they work almost the same way: 给他们相同的名字,他们的工作方式几乎相同:

<label><input type="radio" name="option" value="Option 1">Option 1</label>
<label><input type="radio" name="option" value="Option 2">Option 2</label>

The only significant difference is that, once one of them is selected, at least one of them has to be on (ie, you can't uncheck them again). 唯一重要的区别是,一旦选择其中一个,其中至少有一个必须打开(即,您不能再次取消选中它们)。

If you really feel the need to do it with check boxes, remind yourself that users with JavaScript disabled will be able to select all the options if they like. 如果您真的觉得需要使用复选框,请提醒自己禁用JavaScript的用户可以选择所有选项。 If you still feel the need to do it, then you'll need to give each checkbox group a unique class name. 如果您仍然觉得有必要这样做,那么您需要为每个复选框组分配一个唯一的类名。 Then, handle the change event of each checkbox element and uncheck all the other elements matching the same class name as the clicked element. 然后,处理每个checkbox元素的change事件,并取消选中与单击的元素匹配相同类名的所有其他元素。

Try this: 试试这个:

HTML HTML

<div>
    Car: <input id="chkVehicleCar" name="chkVehicle" type="checkbox" value="Car" class="radiocheckbox">
    Moto: <input id="chkVehicleMoto" name="chkVehicle" type="checkbox" value="Moto" class="radiocheckbox">
    Byke: <input id="chkVehicleByke" name="chkVehicle" type="checkbox" value="Byke" class="radiocheckbox">
    Feet: <input id="chkVehicleFeet" name="chkVehicle" type="checkbox" value="Feet">
</div>

<span>    
    Red: <input id="chkColorRed" name="chkColor" type="checkbox" value="Red" class="radiocheckbox">
    Blue: <input id="chkColorBlue" name="chkColor" type="checkbox" value="Blue" class="radiocheckbox">
    Green: <input id="chkColorGreen" name="chkColor" type="checkbox" value="Green" class="radiocheckbox">

    Mango: <input id="chkFruitMango" name="chkFruit" type="checkbox" value="Mango" class="radiocheckbox">
    Orange: <input id="chkFruitOrange" name="chkFruit" type="checkbox" value="Orange" class="radiocheckbox">
    Banana: <input id="chkFruitBanana" name="chkFruit" type="checkbox" value="Banana" class="radiocheckbox">
</span>

​JavaScript/jQuery 的JavaScript / jQuery的

$(':checkbox.radiocheckbox').click(function() {
    this.checked
        && $(this).siblings('input[name="' + this.name + '"]:checked.' + this.className)
                  .prop('checked', false);
});​

Mutually exclusive checkboxes are grouped by container+name+classname. 互斥复选框按容器+名称+类名分组。 You can use different groups in same container and also mix exclusive with non-exclusive checkbox with same name. 您可以在同一容器中使用不同的组,也可以将具有相同名称的非独占复选框混合使用。 JavaScript code is highly optimized. JavaScript代码经过高度优化。 You can see a working example . 你可以看到一个有效的例子

I hope this one will work 我希望这个会奏效

HTML HTML

A <input type="checkbox" class="alpha" value="A" /> | 
B <input type="checkbox" class="alpha" value="B" /> | 
C <input type="checkbox" class="alpha" value="C" /> 
<br />

1 <input type="checkbox" class="num" value="1" /> |
2 <input type="checkbox" class="num" value="2" /> |
3 <input type="checkbox" class="num" value="3" /> 

JavaScript JavaScript的

// include jQuery library
var enforeMutualExcludedCheckBox = function(group){
    return function() {
      var isChecked= $(this).prop("checked");
      $(group).prop("checked", false);
      $(this).prop("checked", isChecked);
    }
};

$(".alpha").click(enforeMutualExcludedCheckBox(".alpha"));
$(".num").click(enforeMutualExcludedCheckBox(".num"));

well, radio button should be the one to be used in mutually excluded options, though I've encountered a scenario where the client preferred to have zero to one selected item, and the javaScript'ed checkbox works well. 好吧,单选按钮应该是在相互排除的选项中使用的单选按钮,虽然我遇到了一个场景,其中客户端喜欢零到一个选定的项目,并且javaScript的复选框运行良好。

Update 更新

Looking at my answer, I realized it's redundant to refer to the css class twice. 看看我的回答,我意识到两次引用css类是多余的。 I updated my code to convert it into a jquery plugin, and created two solutions, depending on ones preference 我更新了我的代码,将其转换为jquery插件,并根据一个偏好创建了两个解决方案

Get all checkboxes whose check is mutually excluded 获取相互排除检查的所有复选框

$.fn.mutuallyExcludedCheckBoxes = function(){
    var $checkboxes = this; // refers to selected checkboxes

    $checkboxes.click(function() {
      var $this = $(this),
          isChecked = $this.prop("checked");

      $checkboxes.prop("checked", false);
      $this.prop("checked", isChecked);
    });
};

// more elegant, just invoke the plugin
$("[name=alpha]").mutuallyExcludedCheckBoxes();
$("[name=num]").mutuallyExcludedCheckBoxes();

HTML HTML

A <input type="checkbox" name="alpha" value="A" /> | 
B <input type="checkbox" name="alpha" value="B" /> | 
C <input type="checkbox" name="alpha" value="C" /> 
<br />

1 <input type="checkbox" name="num" value="1" /> |
2 <input type="checkbox" name="num" value="2" /> |
3 <input type="checkbox" name="num" value="3" /> 

sample code 示例代码

Group all mutually excluded checkboxes in a containing element 将所有相互排除的复选框分组到包含元素中

JavaScript JavaScript的

$.fn.mutuallyExcludedCheckBoxes = function(){
    var $checkboxes = this.find("input[type=checkbox]");

    $checkboxes.click(function() {
      var $this = $(this),
          isChecked = $this.prop("checked");

      $checkboxes.prop("checked", false);
      $this.prop("checked", isChecked);
    });
};

// select the containing element, then trigger the plugin 
// to set all checkboxes in the containing element mutually 
// excluded
$(".alpha").mutuallyExcludedCheckBoxes();
$(".num").mutuallyExcludedCheckBoxes();

HTML HTML

<div class="alpha">
A <input type="checkbox" value="A" /> | 
B <input type="checkbox" value="B" /> | 
C <input type="checkbox" value="C" /> 
</div>

<div class="num">
1 <input type="checkbox" value="1" /> |
2 <input type="checkbox" value="2" /> |
3 <input type="checkbox" value="3" /> 
</div>

sample code 示例代码

Enjoy :-) 请享用 :-)

No matter where the check box is located on your page, you just need to specify the group and here you go! 无论您的页面上的复选框位于何处,您只需指定组即可!

    <input type='checkbox' data-group='orderState'> pending
    <input type='checkbox' data-group='orderState'> solved
    <input type='checkbox' data-group='orderState'> timed out

    <input type='checkbox' data-group='sex'> male
    <input type='checkbox' data-group='sex'> female

    <input type='checkbox'> Isolated


    <script>
       $(document).ready(function () {
          $('input[type=checkbox]').click(function () {
            var state = $(this)[0].checked, 
                g = $(this).data('group');
             $(this).siblings()
             .each(function () {
     $(this)[0].checked = g==$(this).data('group')&&state ? false : $(this)[0].checked;
             });
  });
 })</script>

I guess this is what you want. 我想这就是你想要的。

Consider the HTML below: 考虑下面的HTML

<form action="">
    My favourite colors are:<br />
    <br />
    <input type="checkbox" value="red" name="color" /> Red<br />
    <input type="checkbox" value="yellow" name="color" /> Yellow<br />
    <input type="checkbox" value="blue" name="color" /> Blue<br />
    <input type="checkbox" value="orange" name="color1" /> Orange<br />
    <input type="checkbox" value="green" name="color1" /> Green<br />
    <input type="checkbox" value="purple" name="color1" /> Purple
</form>

Note that there's two names for color groups: red, yellow, blue and orage, green, purple 请注意,颜色组有两个名称: red, yellow, blueorage, green, purple

And this JavaScript noted below will work generically to all checkbox on the page. 下面提到的这个JavaScript通常适用于页面上的所有checkbox

jQuery("input[type=checkbox]").unbind("click");
jQuery("input[type=checkbox]").each(function(index, value) {
    var checkbox = jQuery(value);
    checkbox.bind("click", function () {
        var check = checkbox.attr("checked");
        jQuery("input[name=" + checkbox.attr('name') + "]").prop("checked", false);
        checkbox.attr("checked", check);
    });
});

Take a look at this LIVE example 看看这个LIVE示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM