【问题标题】:html select only one checkbox in a grouphtml 只选择一个组中的一个复选框
【发布时间】:2012-03-31 08:09:34
【问题描述】:

那么我怎样才能只允许用户只选择一个复选框呢?

我知道单选按钮是“理想的”,但就我的目的而言……它不是。

我有一个字段,用户需要在其中选择一个或两个选项,但不能同时选择两者。问题是我需要我的用户也能够取消选择他们的选项,这就是单选按钮失败的地方,因为一旦你选择了组,你就必须选择一个选项。

我将通过 php 验证信息,但如果用户想给出答案,我仍然希望将其限制为一个答案。

【问题讨论】:

  • 只有 HTML,这是无法做到的。您将需要 JavaScript。如果你对 jQuery 持开放态度,我可以给你一个快速的解决方案。
  • 额外的标记为“none”的单选按钮怎么样?
  • 第三个选项不适合我的设计...虽然不错的选择:)
  • 单选复选框实际上是一个单选按钮。这不会让用户感到惊讶吗?
  • @Surreal Dreams 可以用 HTML 完成,请参阅我的回答。但在大多数情况下,JS 更简单,不需要 hack。

标签: html checkbox


【解决方案1】:

这个 sn-p 将:

  • 允许像单选按钮一样分组
  • 像收音机一样行事
  • 允许取消全选

// the selector will match all input controls of type :checkbox
// and attach a click event handler 
$("input:checkbox").on('click', function() {
  // in the handler, 'this' refers to the box clicked on
  var $box = $(this);
  if ($box.is(":checked")) {
    // the name of the box is retrieved using the .attr() method
    // as it is assumed and expected to be immutable
    var group = "input:checkbox[name='" + $box.attr("name") + "']";
    // the checked state of the group/box on the other hand will change
    // and the current value is retrieved using .prop() method
    $(group).prop("checked", false);
    $box.prop("checked", true);
  } else {
    $box.prop("checked", false);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<div>
  <h3>Fruits</h3>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Kiwi</label>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Jackfruit</label>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Mango</label>
</div>
<div>
  <h3>Animals</h3>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[2][]" />Tiger</label>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[2][]" />Sloth</label>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[2][]" />Cheetah</label>
</div>

【讨论】:

  • 正确的用法是使用 $(this).is(":checked") "is" 来检查 if { ... } else { 中的复选框是否被选中。 .. } 这里 ... jsfiddle.net/zGEaa/31
  • 请注意 .attr 不再有效,请使用 .prop("checked") 代替较新版本的 jQuery
  • @user871784 - 感谢您的提醒...我已经更新了小提琴!
  • 你错过了收音机选择器:$("input:checkbox.radio")
  • @Sven - 在这个例子中它是一个过于具体的选择器。话虽如此,如果页面包含另一组不应具有此行为的复选框,那么使用 .radio 选择器会有所帮助。感谢您指出:)
【解决方案2】:

您希望绑定一个change() 处理程序,以便在复选框状态更改时触发该事件。然后,只需取消选择除触发处理程序的复选框之外的所有复选框:

$('input[type="checkbox"]').on('change', function() {
   $('input[type="checkbox"]').not(this).prop('checked', false);
});

Here's a fiddle


至于分组,如果您的复选框“组”都是兄弟姐妹:

<div>
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
</div>  
<div>
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
</div>   
<div>
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
</div>

你可以这样做:

$('input[type="checkbox"]').on('change', function() {
   $(this).siblings('input[type="checkbox"]').prop('checked', false);
});

Here's another fiddle


如果您的复选框按另一个属性分组,例如name

<input type="checkbox" name="group1[]" />
<input type="checkbox" name="group1[]" />
<input type="checkbox" name="group1[]" />

<input type="checkbox" name="group2[]" />
<input type="checkbox" name="group2[]" />
<input type="checkbox" name="group2[]" />

<input type="checkbox" name="group3[]" />
<input type="checkbox" name="group3[]" />
<input type="checkbox" name="group3[]" />

你可以这样做:

$('input[type="checkbox"]').on('change', function() {
    $('input[name="' + this.name + '"]').not(this).prop('checked', false);
});

Here's another fiddle

【讨论】:

  • 我喜欢你的(最后一个)代码。很短,仍然很清楚。我不确定当您更改其他复选框时 on 'change' 是否会启动,但是当我尝试它时并没有。所以我更喜欢你的代码。谢谢! :)
  • 我真的很喜欢这个,我必须根据自己的需要做一些微调。我有两个项目,因此默认情况下选中第一个项目,如果未选中,则选中第二个项目。这帮助我开始了。
  • 嗨@john.weland - 你的意思是像this这样的东西吗?
  • @billyonecan 几乎完全一样,但能够定位给定的分组。 like this。谢谢
  • 为简单起见加一
【解决方案3】:

已经有一些基于纯 JS 的答案,但没有一个像我希望的那样简洁。

这是我基于使用名称标签(如单选按钮)和几行 javascript 的解决方案。

function onlyOne(checkbox) {
    var checkboxes = document.getElementsByName('check')
    checkboxes.forEach((item) => {
        if (item !== checkbox) item.checked = false
    })
}
<input type="checkbox" name="check" onclick="onlyOne(this)">
<input type="checkbox" name="check" onclick="onlyOne(this)">
<input type="checkbox" name="check" onclick="onlyOne(this)">
<input type="checkbox" name="check" onclick="onlyOne(this)">

【讨论】:

  • 谢谢你,这个是其他人帮我做的 =)
【解决方案4】:

单选按钮是理想的选择。您只需要默认选择的第三个“两者都不”选项。

【讨论】:

  • 这是一个很好的解决方案,但我宁愿坚持使用复选框,因为我的设计不适合第三个选项。
  • 我强烈建议更改设计。 勾选这 2 个选项中的 0 或 1 个 不是一种常见的模式,对用户来说不会像 这 3 个选项中的第 1 个选项那样直观
  • 为什么我要为 2 个复选框更改整个设计?
  • 如果这样的改变需要你改变“你的整个设计”,那么这表明设计一开始就太不灵活了。
  • 它并非不灵活,只是看起来不太对...在表单和此类应用程序上可能看起来不错,但我们的复选框有不同的用法。
【解决方案5】:
$("#myform input:checkbox").change(function() {
    $("#myform input:checkbox").attr("checked", false);
    $(this).attr("checked", true);
});

这应该适用于表单中任意数量的复选框。如果您有其他人不属于该组,请将选择器设置为适用的输入。

【讨论】:

  • 是的先生 :) 没关系,我找到了适合我的东西,尽管您的解决方案看起来很简单。我可能做错了什么。无论如何,谢谢。
  • $("#myform input:checkbox").prop("checked", false);
【解决方案6】:

希望这段代码对您有所帮助。

$(document).ready(function(){
$('.slectOne').on('change', function() {
   $('.slectOne').not(this).prop('checked', false);
   $('#result').html($(this).data( "id" ));
   if($(this).is(":checked"))
   	$('#result').html($(this).data( "id" ));
   else
   	$('#result').html('Empty...!');
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

</head>
<body>
<input type="checkbox" class="slectOne" data-id="1 selected"/>
<input type="checkbox" class="slectOne" data-id="2 selected"/>
<input type="checkbox" class="slectOne" data-id="3 selected"/>
<input type="checkbox" class="slectOne" data-id="4 selected"/>
<input type="checkbox" class="slectOne" data-id="5 selected"/>
<input type="checkbox" class="slectOne" data-id="6 selected"/>
<input type="checkbox" class="slectOne" data-id="7 selected"/>
<input type="checkbox" class="slectOne" data-id="8 selected"/>
<input type="checkbox" class="slectOne" data-id="9 selected"/>
<input type="checkbox" class="slectOne" data-id="10 selected"/>
<span id="result"></span>
</body>
</html>

工作链接Click here

【讨论】:

    【解决方案7】:

    这是我喜欢的简单的 HTML 和 JavaScript 解决方案:

    //js函数一次只允许检查一个工作日复选框:

    function checkOnlyOne(b){
    
    var x = document.getElementsByClassName('daychecks');
    var i;
    
    for (i = 0; i < x.length; i++) {
      if(x[i].value != b) x[i].checked = false;
    }
    }
    
    
    Day of the week:
    <input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Monday" />Mon&nbsp;&nbsp;&nbsp;
    <input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Tuesday" />Tue&nbsp;&nbsp;&nbsp;
    <input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Wednesday" />Wed&nbsp;&nbsp;&nbsp;
    <input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Thursday" />Thu&nbsp;&nbsp;&nbsp;
    <input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Friday" />Fri&nbsp;&nbsp;&nbsp;
    <input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Saturday" />Sat&nbsp;&nbsp;&nbsp;
    <input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Sunday" />Sun&nbsp;&nbsp;&nbsp;<br /><br />
    

    【讨论】:

      【解决方案8】:

      billyonecan 的回答为基础,如果您需要该 sn-p 用于多个复选框(假设它们具有不同的名称),则可以使用以下代码。

          $('input.one').on('change', function() {
              var name = $(this).attr('name');
              $('input[name='+name+'].one').not(this).prop('checked', false);
          }); 
      

      【讨论】:

        【解决方案9】:

        虽然 JS 可能是要走的路,但它可以只用 HTML 和 CSS 来完成。

        这里有一个假单选按钮,它实际上是一个真正隐藏单选按钮的标签。通过这样做,您将获得所需的效果。

        <style>
           #uncheck>input { display: none }
           input:checked + label { display: none }
           input:not(:checked) + label + label{ display: none } 
        </style>
        
        <div id='uncheck'>
          <input type="radio" name='food' id="box1" /> 
          Pizza 
            <label for='box1'>&#9678;</label> 
            <label for='box0'>&#9673;</label>
          <input type="radio" name='food' id="box2" /> 
          Ice cream 
            <label for='box2'>&#9678;</label> 
            <label for='box0'>&#9673;</label>
          <input type="radio" name='food' id="box0" checked />
        </div>
        

        在这里查看:https://jsfiddle.net/tn70yxL8/2/

        现在,假设您需要不可选择的标签。

        如果您愿意包含标签,您可以通过更改 CSS 中的文本从技术上避免重复“取消选中”标签,请参阅此处:https://jsfiddle.net/7tdb6quy/2/

        【讨论】:

          【解决方案10】:

          使用普通的旧 javascript。

          <html>
          <head>
          </head>
          <body>
          <input type="checkbox" name="group1[]" id="groupname1" onClick="toggle(1,'groupname')"/>
          <input type="checkbox" name="group1[]" id="groupname2" onClick="toggle(2,'groupname')"  />
          <input type="checkbox" name="group1[]" id="groupname3" onClick="toggle(3,'groupname')" />
          
          <input type="checkbox" name="group2[]" id="diffGroupname1" onClick="toggle(1,'diffGroupname')"/>
          <input type="checkbox" name="group2[]" id="diffGroupname2" onClick="toggle(2,'diffGroupname')"  />
          <input type="checkbox" name="group2[]" id="diffGroupname3" onClick="toggle(3,'diffGroupname')" />
          <script>
          function toggle(which,group){
          var counter=1;
          var checkbox=document.getElementById(group+counter);
          while(checkbox){
          if(counter==which){
          
          }else{
          checkbox.checked=false;
          }
          counter++;
          checkbox=document.getElementById(group+counter);
          }
          }
          </script>
          </body>
          </html>
          

          编辑:也可以

          <html>
          <head>
          </head>
          <body>
          <input type="checkbox" name="group1[]" class="groupname" onClick="toggle(this,'groupname')"/>
          <input type="checkbox" name="group1[]" class="groupname" onClick="toggle(this,'groupname')"  />
          <input type="checkbox" name="group1[]" class="groupname" onClick="toggle(this,'groupname')" />
          
          <input type="checkbox" name="group2[]" class="diffGroupname" onClick="toggle(this,'diffGroupname')"/>
          <input type="checkbox" name="group2[]" class="diffGroupname" onClick="toggle(this,'diffGroupname')"  />
          <input type="checkbox" name="group2[]" class="diffGroupname" onClick="toggle(this,'diffGroupname')" />
          <script>
          function toggle(which,theClass){
          var checkbox=document.getElementsByClassName(theClass);
          for(var i=0;i<checkbox.length;i++){
          if(checkbox[i]==which){
          
          }else{
          checkbox[i].checked=false;
          }
          }
          }
          </script>
          </body>
          </html>
          

          【讨论】:

            【解决方案11】:

            复选框组

            var group_=(el,callback)=>{
            el.forEach((checkbox)=>{
            callback(checkbox)
                 })
            }
            
            group_(document.getElementsByName('check'),(item)=>{
            item.onclick=(e)=>{
            group_(document.getElementsByName('check'),(item)=>{
            item.checked=false;
            })
            e.target.checked=true;
            
            }
            })
            <input type="checkbox" name="check" >
            <input type="checkbox" name="check" >
            <input type="checkbox" name="check" >
            <input type="checkbox" name="check">

            没有循环的简单复选框

            var last;
            document.addEventListener('input',(e)=>{
            if(e.target.getAttribute('name')=="myRadios"){
            if(last)
            last.checked=false;
            }
            e.target.checked=true;
            last=e.target;
            })
            <input type="checkbox" name="myRadios" value="1" /> 1
            <input type="checkbox" name="myRadios" value="2" /> 2

            按单个 Div 分组

            var group_=(el,callback)=>{
            el.forEach((checkbox)=>{
            callback(checkbox)
                 })
            }
            var group_el=document.querySelectorAll("*[data-name] > input")
            group_(group_el,(item)=>{
            item.onclick=(e)=>{
            group_(group_el,(item)=>{
            item.checked=false;
            })
            
            e.target.checked=true;
            }
            })
            <div data-name="check">
            <input type="checkbox">
            <input type="checkbox">
            <input type="checkbox">
            <input type="checkbox">
            </div>

            css单组div

            var last;
            document.addEventListener('input',(e)=>{
            var closest=e.target.closest("*[data-name='check']");
            console.log(closest)
            if(e.target.closest("*[data-name]")){
            if(last)
            last.checked=false;
            }
            
            e.target.checked=true;
            last=e.target;
            })
            <div data-name="check">
            <input type="checkbox" value="1" /> 1
            <input type="checkbox" value="2" /> 2
            </div>
            选中,取消选中和单个选中框
            var last;
            document.addEventListener('input',(e)=>{
            var closest=e.target.closest("*[data-name='check']");
            if(e.target.closest("*[data-name]")){
            if(last)
            last.checked=false;
            }
            if(e.target!==last)
            last=e.target;
            else
            last=undefined;
            })
            <div data-name="check">
            <input type="checkbox" value="1" /> 1
            <input type="checkbox" value="2" /> 2
            </div>

            【讨论】:

              【解决方案12】:

              AngularJs 示例

              <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
              <!DOCTYPE html>
              <html>
              
              <head>
                <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
                <script>
                  angular.module('app', []).controller('appc', ['$scope',
                    function($scope) {
                      $scope.selected = 'other';
                    }
                  ]);
                </script>
              </head>
              
              <body ng-app="app" ng-controller="appc">
                <label>SELECTED: {{selected}}</label>
                <div>
                  <input type="checkbox" ng-checked="selected=='male'" ng-true-value="'male'" ng-model="selected">Male
                  <br>
                  <input type="checkbox" ng-checked="selected=='female'" ng-true-value="'female'" ng-model="selected">Female
                  <br>
                  <input type="checkbox" ng-checked="selected=='other'" ng-true-value="'other'" ng-model="selected">Other
                </div>
              
              
              
              </body>
              
              </html>

              【讨论】:

                【解决方案13】:

                我的版本:使用数据属性和 Vanilla JavaScript

                <div class="test-checkbox">
                    Group One: <label>
                        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Eat" />Eat</label>
                    <label>
                        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Sleep" />Sleep</label>
                    <label>
                        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Play" />Play</label>
                    <br />
                    Group Two: <label>
                        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Fat" />Fat</label>
                    <label>
                        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Comfort" />Comfort</label>
                    <label>
                        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Happy" />Happy</label>
                </div>
                <script>
                    let cbxes = document.querySelectorAll('input[type="checkbox"][data-limit="only-one-in-a-group"]');
                    [...cbxes].forEach((cbx) => {
                        cbx.addEventListener('change', (e) => {
                            if (e.target.checked)
                                uncheckOthers(e.target);
                        });
                    });
                    function uncheckOthers (clicked) {
                        let name = clicked.getAttribute('name');
                        // find others in same group, uncheck them
                        [...cbxes].forEach((other) => {
                            if (other != clicked && other.getAttribute('name') == name)
                                other.checked = false;
                        });
                    }
                </script>
                

                【讨论】:

                  【解决方案14】:

                  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
                  <!DOCTYPE html>
                  <html>
                  
                  <head>
                    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
                    <script>
                      angular.module('app', []).controller('appc', ['$scope',
                        function($scope) {
                          $scope.selected = 'male';
                        }
                      ]);
                    </script>
                  </head>
                  
                  <body ng-app="app" ng-controller="appc">
                    <label>SELECTED: {{selected}}</label>
                    <div>
                      <input type="checkbox" ng-checked="selected=='male'" ng-true-value="'male'" ng-model="selected">Male
                      <br>
                      <input type="checkbox" ng-checked="selected=='female'" ng-true-value="'female'" ng-model="selected">Female
                      <br>
                      <input type="checkbox" ng-checked="selected=='other'" ng-true-value="'other'" ng-model="selected">Other
                    </div>
                  </body>
                  </html>

                  【讨论】:

                    【解决方案15】:

                    如果有人需要没有外部 javascript 库的解决方案,您可以使用此示例。一组允许 0..1 个值的复选框。您可以点击复选框组件或相关的标签文本。

                        <input id="mygroup1" name="mygroup" type="checkbox" value="1" onclick="toggleRadioCheckbox(this)" /> <label for="mygroup1">Yes</label>
                        <input id="mygroup0" name="mygroup" type="checkbox" value="0" onclick="toggleRadioCheckbox(this)" /> <label for="mygroup0">No</label>
                    
                    - - - - - - - - 
                    
                        function toggleRadioCheckbox(sender) {
                            // RadioCheckbox: 0..1 enabled in a group 
                            if (!sender.checked) return;
                            var fields = document.getElementsByName(sender.name);
                            for(var idx=0; idx<fields.length; idx++) {
                                var field = fields[idx];
                                if (field.checked && field!=sender)
                                    field.checked=false;
                            }
                        }
                    

                    【讨论】:

                      【解决方案16】:

                      死灵术:
                      没有 jQuery,对于这样的复选框结构:

                      <label>
                      <input type="checkbox" id="mytrackers_1" name="blubb_1" value="">--- Bitte ausw&#228;hlen ---
                      </label>
                      <label>
                      <input type="checkbox" id="mytrackers_2" name="blubb_2" value="7">Testtracker
                      </label>
                      <label>
                      <input type="checkbox" id="mytrackers_3" name="blubb_3" value="3">Kundenanfrage
                      </label>
                      <label>
                      <input type="checkbox" id="mytrackers_4" name="blubb_4" value="2">Anpassung
                      </label>
                      <label>
                      <input type="checkbox" id="mytrackers_5" name="blubb_5" value="1" checked="checked" >Fehler
                      </label>
                      <label>
                      <input type="checkbox" id="mytrackers_6" name="blubb_6" value="4">Bedienung
                      </label>
                      <label>
                      <input type="checkbox" id="mytrackers_7" name="blubb_7" value="5">Internes
                      </label>
                      <label>
                      <input type="checkbox" id="mytrackers_8" name="blubb_8" value="6">&#196;nderungswunsch
                      </label>
                      

                      你会这样做:

                          /// attach an event handler, now or in the future, 
                          /// for all elements which match childselector,
                          /// within the child tree of the element maching parentSelector.
                          function subscribeEvent(parentSelector, eventName, childSelector, eventCallback) {
                              if (parentSelector == null)
                                  throw new ReferenceError("Parameter parentSelector is NULL");
                              if (childSelector == null)
                                  throw new ReferenceError("Parameter childSelector is NULL");
                              // nodeToObserve: the node that will be observed for mutations
                              var nodeToObserve = parentSelector;
                              if (typeof (parentSelector) === 'string')
                                  nodeToObserve = document.querySelector(parentSelector);
                              var eligibleChildren = nodeToObserve.querySelectorAll(childSelector);
                              for (var i = 0; i < eligibleChildren.length; ++i) {
                                  eligibleChildren[i].addEventListener(eventName, eventCallback, false);
                              } // Next i 
                              // https://stackoverflow.com/questions/2712136/how-do-i-make-this-loop-all-children-recursively
                              function allDescendants(node) {
                                  if (node == null)
                                      return;
                                  for (var i = 0; i < node.childNodes.length; i++) {
                                      var child = node.childNodes[i];
                                      allDescendants(child);
                                  } // Next i 
                                  // IE 11 Polyfill 
                                  if (!Element.prototype.matches)
                                      Element.prototype.matches = Element.prototype.msMatchesSelector;
                                  if (node.matches) {
                                      if (node.matches(childSelector)) {
                                          // console.log("match");
                                          node.addEventListener(eventName, eventCallback, false);
                                      } // End if ((<Element>node).matches(childSelector))
                                      // else console.log("no match");
                                  } // End if ((<Element>node).matches) 
                                  // else console.log("no matchfunction");
                              } // End Function allDescendants 
                              // Callback function to execute when mutations are observed
                              var callback = function (mutationsList, observer) {
                                  for (var _i = 0, mutationsList_1 = mutationsList; _i < mutationsList_1.length; _i++) {
                                      var mutation = mutationsList_1[_i];
                                      // console.log("mutation.type", mutation.type);
                                      // console.log("mutation", mutation);
                                      if (mutation.type == 'childList') {
                                          for (var i = 0; i < mutation.addedNodes.length; ++i) {
                                              var thisNode = mutation.addedNodes[i];
                                              allDescendants(thisNode);
                                          } // Next i 
                                      } // End if (mutation.type == 'childList') 
                                      // else if (mutation.type == 'attributes') { console.log('The ' + mutation.attributeName + ' attribute was modified.');
                                  } // Next mutation 
                              }; // End Function callback 
                              // Options for the observer (which mutations to observe)
                              var config = { attributes: false, childList: true, subtree: true };
                              // Create an observer instance linked to the callback function
                              var observer = new MutationObserver(callback);
                              // Start observing the target node for configured mutations
                              observer.observe(nodeToObserve, config);
                          } // End Function subscribeEvent 
                      
                      
                          function radioCheckbox_onClick() 
                          { 
                              // console.log("click", this);
                              let box = this;
                              if (box.checked) 
                              {
                                  let name = box.getAttribute("name");
                                  let pos = name.lastIndexOf("_");
                                  if (pos !== -1) name = name.substr(0, pos);
                      
                                  let group = 'input[type="checkbox"][name^="' + name + '"]';
                                  // console.log(group);
                                  let eles = document.querySelectorAll(group);
                                  // console.log(eles);
                                  for (let j = 0; j < eles.length; ++j) 
                                  {
                                      eles[j].checked = false;
                                  }
                                  box.checked = true;
                              }
                              else
                                  box.checked = false;
                          }
                      
                      
                          // https://stackoverflow.com/questions/9709209/html-select-only-one-checkbox-in-a-group
                          function radioCheckbox()
                          { 
                              // on instead of document...
                              let elements = document.querySelectorAll('input[type="checkbox"]')
                      
                              for (let i = 0; i < elements.length; ++i)
                              {
                                  // console.log(elements[i]);
                                  elements[i].addEventListener("click", radioCheckbox_onClick, false);
                      
                              } // Next i 
                      
                          } // End Function radioCheckbox 
                      
                      
                          function onDomReady()
                          {
                              console.log("dom ready");
                              subscribeEvent(document, "click", 
                                  'input[type="checkbox"]', 
                                  radioCheckbox_onClick
                              ); 
                      
                              // radioCheckbox();
                          }
                      
                          if (document.addEventListener) document.addEventListener("DOMContentLoaded", onDomReady, false);
                          else if (document.attachEvent) document.attachEvent("onreadystatechange", onDomReady);
                          else window.onload = onDomReady;
                      
                          function onPageLoaded() {
                              console.log("page loaded");
                          }
                      
                          if (window.addEventListener) window.addEventListener("load", onPageLoaded, false);
                          else if (window.attachEvent) window.attachEvent("onload", onPageLoaded);
                          else window.onload = onPageLoaded;
                      

                      【讨论】:

                        【解决方案17】:
                        //Here is a solution using JQuery    
                        <input type = "checkbox" class="a"/>one
                            <input type = "checkbox" class="a"/>two
                            <input type = "checkbox" class="a"/>three
                            <script>
                               $('.a').on('change', function() {
                                    $('.a').not(this).prop('checked',false);
                            });
                            </script>
                        

                        【讨论】:

                          【解决方案18】:

                          下面的代码 sn-p 演示了一种在组中仅选择一个复选框的简单方法。


                            <!DOCTYPE html>
                          <html>
                          <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
                          <body>
                              <h3>Demonstration of Checkbox Toggle</h3>
                              <p>
                                  <span><b>Letters:</b></span>
                                  A<input type="checkbox" name="A" >
                                  B<input type="checkbox" name="B" >
                                  C<input type="checkbox" name="C" >
                                  D<input type="checkbox" name="D" >
                              </p>
                              <p>
                                  <span><b>Numbers:</b></span>
                                  1<input type="checkbox" name="1" >
                                  2<input type="checkbox" name="2" >
                                  3<input type="checkbox" name="3" >
                              </p>
                               <p>
                                  <span><b>Birds:</b></span>
                                  Scarlet Ibis<input type="checkbox" name="Scarlet Ibis" >
                                  Cocrico <input type="checkbox" name="Cocrico" >
                                  hummingbird <input type="checkbox" name="hummingbird" >
                              </p>
                          </body>
                          
                          <script>
                              $(function()
                              {
                                  function toggle(choices,name) 
                                  {
                                      if(choices.includes(name))
                                      {
                                          for( i=0;i<choices.length;i++)
                                          {
                                          if(name !=choices[i])
                                              $('input[name="' + choices[i] + '"]').not(this).prop('checked', false); 
                                          }
                                      }
                                  }
                                  $('input[type="checkbox"]').on('change', function() 
                                  {
                                      var letters = ["A","B","C","D"];
                                      var numbers = ["1", "2", "3"];
                                      var birds = ["Scarlet Ibis", "Cocrico", "hummingbird"];
                                      
                                      toggle(letters,this.name);
                                      toggle(numbers,this.name);
                                      toggle(birds,this.name);
                                  });
                          
                              });
                          </script>
                          </html>

                          【讨论】:

                            【解决方案19】:

                            这是我的代码:

                            <label>Select Unit </label>
                                    <div class="row">
                                        <div class="col-md-4">
                                            <input type="checkbox" class="group1" checked  /> Meters
                                        </div>
                                        <div class="col-md-4">
                                            <input type="checkbox" class="group1"/> Pieces
                                        </div>
                                        <div class="col-md-4">
                                            <input type="checkbox" class="group1" /> cm
                                        </div>
                                    </div>
                                    <br />
                            

                            和两行 javascript

                            $('input[type="checkbox"]').on('change', function () {
                                $(this).parent().siblings('div').children('input[type="checkbox"]').not(this).prop('checked', false);
                            });
                            

                            【讨论】:

                              猜你喜欢
                              • 2015-06-06
                              • 1970-01-01
                              • 2017-08-10
                              • 2013-10-21
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              相关资源
                              最近更新 更多