【问题标题】:make checkbox behave like radio buttons with javascript使复选框的行为类似于带有 javascript 的单选按钮
【发布时间】:2011-08-15 22:36:56
【问题描述】:

我需要使用 javascript 来操作复选框的行为。它们基本上应该像单选按钮一样(一次只能选择一个,加上取消选择之前的任何选择)。

问题是我不能首先使用普通的单选按钮,因为每个单选按钮的名称属性会有所不同。

我知道它不是让苹果看起来像梨的终极和最闪亮的解决方案,w3c 不会给我他们的拇指,但它现在会比现在更好的解决方案改变整个cms结构的核心php逻辑;-)

非常感谢任何帮助!

【问题讨论】:

  • 您是否使用了这样的框架(例如 jQuery)。我不会告诉您将 jQuery 或任何其他框架添加到您的项目中以完成诸如此之类的简单任务,除非您正在使用一个。

标签: javascript html


【解决方案1】:

HTML:

<label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label>
<label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label>
<label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label>
<label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label>

jQuery :

$(".chb").change(function() {
    $(".chb").prop('checked', false);
    $(this).prop('checked', true);
});

如果您希望用户可以取消选中所选项目:

$(".chb").change(function() {
    $(".chb").not(this).prop('checked', false);
});

演示:

http://jsfiddle.net/44Zfv/724/

【讨论】:

  • 不错的小提琴,+如果你想再次取消选中复选框(这段代码几乎完美,除了不允许取消选中所有)添加:if($(this).attr('checked'))
  • 请注意 .attr 不再有效,请使用 .prop("checked") 代替较新版本的 jQuery
  • @MikeCampbell 确定添加 ;)
  • 可以简化为$(".chb").change(function(),而不是$(".chb").each(function(){ $(this).change(function(),但是很好。
  • @D.A.V.O.O.D 5 年了.. 但是代码现在不起作用 - 有人可以更新它吗?谢谢。
【解决方案2】:

有很多方法可以做到这一点。这是一个包含多个复选框的 div 的 clickhandler (plain js):

function cbclick(e){
   e = e || event;
   var cb = e.srcElement || e.target;
   if (cb.type !== 'checkbox') {return true;}
   var cbxs = document.getElementById('radiocb')
               .getElementsByTagName('input'), 
       i    = cbxs.length;
    while(i--) {
        if (cbxs[i].type 
             && cbxs[i].type == 'checkbox' 
             && cbxs[i].id !== cb.id) {
          cbxs[i].checked = false;
        }
    }
}

这里是a working example

【讨论】:

    【解决方案3】:

    我保持简单......

    <html>
    <body>
    
    <script>
    function chbx(obj)
    {
    var that = obj;
       if(document.getElementById(that.id).checked == true) {
          document.getElementById('id1').checked = false;
          document.getElementById('id2').checked = false;
          document.getElementById('id3').checked = false;
          document.getElementById(that.id).checked = true;
       }
    }
    </script>
    
    <form action="your action" method="post">
    
    <Input id='id1' type='Checkbox' Name ='name1' value ="S" onclick="chbx(this)"><br />
    <Input id='id2' type='Checkbox' Name ='name2' value ="S" onclick="chbx(this)"><br />
    <Input id='id3' type='Checkbox' Name ='name3' value ="S" onclick="chbx(this)"><br />
    
    <input type="submit" value="Submit" />
    </form>
    
    </body>
    </html>
    

    【讨论】:

    • 一些关于你的方法如何工作的支持信息在这种情况下可能有用
    • 帮助我解决了一百个问题
    【解决方案4】:

    这是一个更好的选择,因为它还允许取消选中:

    $(".cb").change(function () {
        $(".cb").not(this).prop('checked', false);
    });
    

    【讨论】:

      【解决方案5】:

      @DJafari 的回答不允许取消选中该复选框。所以我更新了它:

      $(".chb").change(function(e) {
      
       //Getting status before unchecking all
        var status = $(this).prop("checked");
      
        $(".chb").prop('checked', false);
        $(this).prop('checked', true);
      
       //false means checkbox was checked and became unchecked on change event, so let it stay unchecked
        if (status === false) {
          $(this).prop('checked', false);
        }
      
      });
      

      https://jsfiddle.net/mapetek/nLtb0q1e/4/

      【讨论】:

        【解决方案6】:

        以防万一帮助别人

        我遇到了同样的情况,我的客户需要 checkbox 的行为类似于 radio button。但对我来说,使用checkbox 并使其表现得像radio button 毫无意义,而且对我来说非常复杂,因为我在GridView 控件中使用了这么多checkboxes

        我的解决方案:
        因此,我将radio button 的样式设置为类似于checkbox,并借助了grouping 的单选按钮。

        【讨论】:

          【解决方案7】:

          你可以给你需要这样行为的复选框组一个公共类,然后使用该类来附加以下事件处理程序:

          function clickReset ()
          {
              var isChecked = false,
                  clicked = $(this),
                  set = $('.' + clicked.attr ('class') + ':checked').not (clicked);
          
              if (isChecked = clicked.attr ('checked'))
              {
                  set.attr ('checked', false);
              }
              return true;
          }
          
          $(function ()
          {
              $('.test').click (clickReset);
          });
          

          注意:这很漂亮,我只是从臀部射击,我没有测试过它,它可能需要调整才能工作。

          如果可以的话,我建议您考虑找到一种使用单选按钮执行此操作的方法,因为收音机是完成这项工作的合适工具。用户希望复选框的行为类似于复选框,而不是收音机,如果他们关闭 javascript,他们可以强制通过输入到您不期望的服务器端脚本中。

          编辑:修复功能,以便取消选中正常工作并添加 JS Fiddle 链接。

          http://jsfiddle.net/j53gd/1/

          【讨论】:

          • 当点击一个选中的复选框时,复选框不必丢失选中
          【解决方案8】:
          <html>
          <body>
          
          <form action="#" method="post">
          Radio 1: <input type="radio" name="radioMark" value="radio 1" /><br />
          Radio 2: <input type="radio" name="radioMark" value="radio 2" /><br />
          <input type="submit" value="Submit" />
          </form>
          
          </body>
          </html>
          

          最终,您可以使用带有 name 属性的括号来创建一个无线电输入数组,如下所示:

          <input type="radio" name="radioMark[]" value="radio1" />Radio 1
          <input type="radio" name="radioMark[]" value="radio2" />Radio 2
          <input type="radio" name="radioMark[]" value="radio3" />Radio 3
          <input type="radio" name="radioMark[]" value="radio4" />Radio 4
          

          最终要传递的是 value 属性中的内容。每个单选按钮的名称不必完全不同。希望对您有所帮助。

          【讨论】:

            【解决方案9】:

            在简单的 JS 中。 享受 !

            <!DOCTYPE html>
            <html>
            <head>
            <script type="text/javascript">
                    function onChoiceChange(obj) {
                        // Get Objects
                        var that=obj,
                            triggerChoice = document.getElementById(that.id),
                            domChoice1 = document.getElementById("Choice1"),
                            domChoice2 = document.getElementById("Choice2");
                        // Apply
                        if (triggerChoice.checked && triggerChoice.id === "Choice1") 
                            domChoice2.checked=false;
                        if (triggerChoice.checked && triggerChoice.id === "Choice2") 
                            domChoice1.checked=false;
                        // Logout
                        var log = document.getElementById("message");
                        log.innerHTML += "<br>"+ (domChoice1.checked ? "1" : "0") + ":" + (domChoice2.checked ? "1" : "0");
                        // Return !
                        return that.checked;
                    }
                </script>
            </head>
            <body>
                <h1 id="title">Title</h1>
                <label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice1" />Choice #1</label> 
                <label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice2" />Choice #2</label>
                <hr>
                <div id="message"></div>
            </body>
            </html>
            

            【讨论】:

            • 请说明您认为您的代码解决问题的原因。
            【解决方案10】:

            试试这个

            <form id="form" action="#">
                        <input name="checkbox1" type="checkbox" />
                        <input name="checkbox2" type="checkbox" />
                        <input name="checkbox3" type="checkbox" />
                        <input name="checkbox4" type="checkbox" />
                        <input name="checkbox5" type="checkbox" />
                        <input name="checkbox6" type="checkbox" />
                        <input name="checkbox7" type="checkbox" />
                        <input name="checkbox8" type="checkbox" />
                        <input name="checkbox9" type="checkbox" />
                        <input name="checkbox10" type="checkbox" />
                        <input type="submit" name="submit" value="submit"/>
                    </form>
            

            这是 javascript

            (function () {
                function checkLikeRadio(tag) {
                    var form = document.getElementById(tag);//selecting the form ID 
                    var checkboxList = form.getElementsByTagName("input");//selecting all checkbox of that form who will behave like radio button
                    for (var i = 0; i < checkboxList.length; i++) {//loop thorough every checkbox and set there value false. 
                        if (checkboxList[i].type == "checkbox") {
                            checkboxList[i].checked = false;
                        }
                        checkboxList[i].onclick = function () {
                            checkLikeRadio(tag);//recursively calling the same function again to uncheck all checkbox
                            checkBoxName(this);// passing the location of selected checkbox to another function. 
                        };
                    }
                }
            
                function checkBoxName(id) {
                    return id.checked = true;// selecting the selected checkbox and maiking its value true; 
                }
                window.onload = function () {
                    checkLikeRadio("form");
                };
            })();
            

            【讨论】:

              【解决方案11】:

              我喜欢D.A.V.O.O.D's Answer to this question,但它依赖于复选框上的类,这不应该是必需的。

              由于复选框往往是相关的,因为它们将具有相同的(字段)名称,或者使它们成为数组一部分的名称,因此使用它来决定取消选中哪些其他复选框将是一个更好的解决方案。

              $(document)
                .on('change','input[type="checkbox"]',function(e){
                  var $t = $(this);
                  var $form = $t.closest('form');
                  var name = $t.attr('name');
                  var selector = 'input[type="checkbox"]';
                  var m = (new RegExp('^(.+)\\[([^\\]]+)\\]$')).exec( name );
                  if( m ){
                    selector += '[name^="'+m[1]+'["][name$="]"]';
                  }else{
                    selector += '[name="'+name+'"]';
                  }
                  $(selector, $form).not($t).prop('checked',false);
                });
              

              This code on jsFiddle

              【讨论】:

                猜你喜欢
                • 2014-06-24
                • 1970-01-01
                • 1970-01-01
                • 2014-12-12
                • 2014-12-15
                • 1970-01-01
                • 2020-04-07
                • 1970-01-01
                • 2020-03-24
                相关资源
                最近更新 更多