【问题标题】:Enable single or multiple checkboxes checked based on radio button启用基于单选按钮检查的单个或多个复选框
【发布时间】:2014-10-08 12:30:54
【问题描述】:

我有一个带有单选按钮和复选框的简单表单,用户可以在其中选择下载单个或多个语言包。如果选择了单个选项,则复选框的行为应类似于单选按钮,并且只能勾选一个复选框。如果用户选择多选项,他/她可以勾选任意数量的复选框。如何使用 JQuery/JavaScript 实现这一点?任何帮助将不胜感激,因为我对此完全陌生。这是简单的 HTML 表单:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org    /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
    </head>
    <body>
        <p>Language options:</p>
        <form id="form1" name="form1" method="post" action="">
            <p>
                <label>
                <input type="radio" name="langOptionRadioBtn" value="Single" id="langOptionRadioBtn_0" />
                Single</label>

                <label>
                <input type="radio" name="langOptionRadioBtn" value="Multi" id="langOptionRadioBtn_1" />
                Multi</label>

                <br />
            </p>
        </form>
        <p>Languages: </p>
        <form id="form2" name="form2" method="post" action="">
            <p>
                <label>
                <input type="checkbox" name="langCheckBoxes" value="English" id="langCheckBoxes_0" />
                English</label>

                <br />
                <label>
                <input type="checkbox" name="langCheckBoxes" value="French" id="langCheckBoxes_1" />
                French</label>

                <br />
                <label>
                <input type="checkbox" name="langCheckBoxes" value="Spanish" id="langCheckBoxes_2" />
                Spanish</label>

                <br />
                <label>
                <input type="checkbox" name="langCheckBoxes" value="Russian" id="langCheckBoxes_3" />
                Russian</label>

                <br />
                <label>
                <input type="checkbox" name="langCheckBoxes" value="Arabic" id="langCheckBoxes_4" />
                Arabic</label>

                <br />
                <label>
                <input type="checkbox" name="langCheckBoxes" value="Chinese" id="langCheckBoxes_5" />
                Chinese</label>

                <br />
            </p>
        </form>
    </body>
</html>

【问题讨论】:

    标签: javascript jquery html checkbox radio-button


    【解决方案1】:

    您只需要在点击时切换输入类型:

    $("#langOptionRadioBtn_0").click(function(){
        $('#form2 input[type="checkbox"]').each(function(){
            $(this).prop("type", "radio");
        });
    });
    
    $("#langOptionRadioBtn_1").click(function(){
        $('#form2 input[type="radio"]').each(function(){
            $(this).prop("type", "checkbox");
        });
    });
    

    您可以在http://jsfiddle.net/um1qgexr/ 现场测试代码。

    【讨论】:

    • 他询问了checkbox
    • 是的,用户确实要求复选框,这是否意味着这是正确的解决方案?不,因为以下原因: 1. 可用性:所有基本的 HTML 输入都应该按预期运行,这意味着不要让用户只使用 1 个复选框来混淆用户。这对用户来说是反直觉的,这可能会导致糟糕的用户体验。 2. 简单:不需要额外的逻辑来强制只有1个复选框,我们让标准来处理它。更少的代码意味着更少的维护和更少的可能出错的事情。
    【解决方案2】:

    一种快速简单的方法是在您选择其中一种时更改类型。

    <label>
        <input type="radio" name="langOptionRadioBtn" value="Single" id="langOptionRadioBtn_0" onclick="updateBoxes('radio');" />
        Single
    </label>
    <label>
          <input type="radio" name="langOptionRadioBtn" value="Multi" id="langOptionRadioBtn_1" onclick="updateBoxes('checkbox');" />
    Multi
    

    然后是更新框的函数

    function updateBoxes(type) {
        var boxes = document.getElementById( 'form2' ).getElementsByTagName( 'input' );
        for( var i=0; i<boxes.length; i++ ) {
            boxes[i].type=type;
            boxes[i].checked = false;
        }
    }
    

    【讨论】:

      【解决方案3】:

      给你:DEMO

      $('input[type=checkbox]').change(function(e){
          if($('input[type=radio]:checked').length==0){ 
              $(this).prop('checked',!$(this).prop('checked'));
              return false;
          }
          else if($('input[type=radio]:checked').val()=='Single'){
              $('input[type=checkbox]').not(this).prop('checked',false);
          }
      });
      $('input[type=radio]').click(function(){
          $('input[type=checkbox]').prop('checked',false);
      });
      

      这里如果你点击任何一个单选按钮,所有的复选框都会被取消选中,如果没有一个单选按钮被选中,用户就不能选择一个复选框,其余的按照问题中的要求。

      【讨论】:

        【解决方案4】:

        首先,您不需要两个单独的表格。听起来所有数据都应该发送到同一个地方,因此没有理由将单选按钮和复选框包装在单独的 &lt;form&gt; 标签中。您的标记可能如下所示:

        <p>Language options:</p>
        <form id="form1" name="form1" method="post" action="">
          <p>
            <label>
              <input type="radio" name="langOptionRadioBtn" value="Single" id="langOptionRadioBtn_0" />
              Single</label>
            <label>
              <input type="radio" name="langOptionRadioBtn" value="Multi" id="langOptionRadioBtn_1" />
              Multi</label>
            <br />
          </p>
        <p>Languages: </p>
          <p>
            <label>
              <input type="checkbox" name="langCheckBoxes" value="English" id="langCheckBoxes_0" />
              English</label>
            <br />
                <label>
              <input type="checkbox" name="langCheckBoxes" value="French" id="langCheckBoxes_1" />
              French</label>
            <br />
            <label>
              <input type="checkbox" name="langCheckBoxes" value="Spanish" id="langCheckBoxes_2" />
              Spanish</label>
            <br />
            <label>
              <input type="checkbox" name="langCheckBoxes" value="Russian" id="langCheckBoxes_3" />
              Russian</label>
            <br />
            <label>
              <input type="checkbox" name="langCheckBoxes" value="Arabic" id="langCheckBoxes_4" />
          Arabic</label>
            <br />
            <label>
              <input type="checkbox" name="langCheckBoxes" value="Chinese" id="langCheckBoxes_5" />
              Chinese</label>
            <br />
           </p>
        </form>
        

        这里是 jQuery 代码,您可以使用它来执行您建议的操作。这个想法是,每次用户单击复选框时,我们都会检查是否选择了 multi。如果是,那么我们不必更改复选框的行为,但如果不是,则我们清除除用户实际选择的复选框之外的所有复选框。

        var $form = $('#form1');
        var $checkboxes = $('input[type=checkbox]');
        var $selectionType = $('input[type=radio]');
        var $output = $('#output');
        var isMulti = false;
        
        
        
        // Listen to change event on the radio buttons and set isMulti
        $selectionType.on('change', function( e ) {
            // Check the value of what radio button was clicked
            isMulti = $( e.target ).val() === 'Multi';
        
            // Clear all selected checkboxes if user clicked "single"
            if( !isMulti ) {
                $checkboxes.each( function( idx, item ) {
                    $( item ).prop( 'checked', false );
                });
            }
        });
        
        // Listen to clicks on checkboxes
        $checkboxes.on('change', function( e ) {
        
            // Store what was just clicked
            var $this = $( e.target );
        
            // If Multi is not selected, then remove the check from all other checkboxes
            if( !isMulti ) {
        
                $checkboxes.each( function( idx, item ) {
        
                    var $item = $( item );
        
                    // Do not un check if this is the checkbox the user clicked
                    if( $item.attr('id') === $this.attr('id') ) {
                        return true;
                    }
        
                    $item.prop('checked', false );
                });
            }
        });
        

        这是一个运行它的 JS 小提琴:http://jsfiddle.net/grammar/pdx8gccu/2/

        希望这会有所帮助!

        【讨论】:

          【解决方案5】:

          我看到这里的答案,说改变收音机,但也可以用复选框:

          var allowMultiLang = false;
          
          $('#form1 input[type=radio]').on('change', function() {
            // get the selected radio
            var selectedRadio = $('input[type=radio]:checked');
            // if the selected is 'Single'
            if(selectedRadio.val() == 'Single') {
              allowMultiLang = false;
              // uncheck all
              $('#form2 input[type=checkbox]:checked').prop('checked', false);
            // if the selected is 'Multi'
            } else if(selectedRadio.val() == 'Multi') {
              allowMultiLang = true;
            }
          
          });
          
          $('#form2 input[type=checkbox]').on('change', function() {
            if(allowMultiLang === false) {
              if($(this).is(':checked')) {
                // uncheck all BUT this
                $('#form2 input[type=checkbox]').not(this).prop('checked', false);
              }
            }
          });
          

          演示:http://jsfiddle.net/b5Le3uLb/

          【讨论】:

            【解决方案6】:

            我写的方式如下:
            1)查找选择了哪个单选按钮。
            2)如果之前选中了复选框并且选中的复选框的数量更大 大于 1,然后清除所有复选框。
            3)选择单个选项时,然后调用一个方法取消选择复选框的其余部分。
            4)当多选项被选中时,然后取消绑定导致取消选中其他复选框的方法,从而可以选中多个复选框。

            我知道我的代码很长,但是我认为它可以帮助您入门,而且它也易于阅读。

            小提琴的示例是

            $('.language_options').on('click', function() {
            
            
            ClearCheckBoxes();
            
            if(this.id=='langOptionRadioBtn_0')
            {
                $('input[name="langCheckBoxes"]').on('change', function() {
                    ClearOtherCheckBoxes(this,'single');
            
                });
            
            }
            else
            {
                 $('input[name="langCheckBoxes"]').unbind();
            }
            

            });

            这里是小提琴链接。

            http://jsfiddle.net/5wadfh3o/16/


            这是在 FireFox 31.0 上测试的

            谢谢。

            【讨论】:

              猜你喜欢
              • 2013-05-10
              • 1970-01-01
              • 2012-03-13
              • 2017-12-28
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-05-29
              • 2020-07-06
              相关资源
              最近更新 更多