Javascript 如何使一组复选框互斥?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8077919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:38:25  来源:igfitidea点击:

How can I make a group of checkboxes mutually exclusive?

javascriptjquery

提问by sajad

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. 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

我决定使用 ajax 互斥复选框扩展器。目前给出的解决方案基本上都是基于单选按钮。这个链接真的帮助了我.. http://www.asp.net/ajax/videos/how-do-i-use-the-aspnet-ajax-mutuallyexclusive-checkbox-extender

采纳答案by Rupesh Pawar

Using Mutual Checkboxes when there is Radio button is a bad idea but still you can do this as follows

当有单选按钮时使用相互复选框是一个坏主意,但您仍然可以按如下方式执行此操作

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

查询

$('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

这是小提琴

回答by Andy E

Like I said in my comment, you should really use <radio>elements for this. Give them the same name and they work almost the same way:

就像我在评论中所说的那样,您真的应该<radio>为此使用元素。给它们起相同的名字,它们的工作方式几乎相同:

<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. If you stillfeel 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.

如果您真的觉得需要使用复选框来完成,请提醒自己禁用 JavaScript 的用户可以根据需要选择所有选项。如果您仍然觉得有必要这样做,那么您需要为每个复选框组指定一个唯一的类名。然后,处理每个复选框元素的更改事件,并取消选中与单击元素具有相同类名的所有其他元素。

回答by Gianni Gentile

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. You can see a working example.

互斥复选框按容器+名称+类名分组。您可以在同一个容器中使用不同的组,也可以将独占与具有相同名称的非独占复选框混合使用。JavaScript 代码经过高度优化。您可以看到一个工作示例

回答by OnesimusUnbound

I hope thisone 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. I updated my code to convert it into a jquery plugin, and created two solutions, depending on ones preference

看着我的回答,我意识到两次引用 css 类是多余的。我更新了代码以将其转换为 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 :-)

享受 :-)

回答by Abdul Munim

I guess this is what you want.

我想这就是你想要的。

Consider the HTMLbelow:

考虑下面的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, blueand orage, green, purple

请注意,颜色组有两个名称:red, yellow, blueorage, green, purple

And this JavaScript noted below will work generically to all checkboxon 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 例子

回答by Bellash

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>