How can I make a group of checkboxes mutually exclusive?

前端 未结 6 1945
名媛妹妹
名媛妹妹 2020-12-16 11:54

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

6条回答
  •  孤城傲影
    2020-12-16 12:02

    I hope this one will work

    HTML

    A  | 
    B  | 
    C  
    
    1 | 2 | 3

    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.

    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

    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

    A  | 
    B  | 
    C  
    
    1 | 2 | 3

    sample code

    Group all mutually excluded checkboxes in a containing element

    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

    A | B | C
    1 | 2 | 3

    sample code

    Enjoy :-)

提交回复
热议问题