douhao6557 2016-12-08 14:41
浏览 84

无法限制要选择的复选框的数量

I'm using foreach loop to generate the checkboxes in my form. It is given below.

<?php $index = 0;
foreach($cameramen as $n_key){ ?>
    <div class="checkbox">
        <label>
            <input type="checkbox" id="cameramen_<?php echo $index+1; ?>" name="cameramen" class="subscriber" value="<?php echo $index+1; ?>">

            <?php 
                echo $n_key->emplist3; 
                $index++;
            ?>

        </label>
    </div>
    <br/><br/>
<?php } ?>  

I want to limit the number of checkboxes to be selected by the user to two. I used the following javascript function but it not worked(It allows to select all the checkboxes).

 $("input[name=cameramen]").change(function(){
    var max= 2;
    console.log($("input[name=cameramen]:checked").length);
    if( $("input[name=cameramen]:checked").length == max ){
        $("input[name=cameramen]").attr('disabled', 'true');
        $("input[name=cameramen]:checked").removeAttr('disabled');
    }else{
         $("input[name=cameramen]").removeAttr('disabled');
    }
  });

Someone please help me to solve this problem which I have being struggling for hours to solve.

  • 写回答

1条回答 默认 最新

  • dongwei6457 2016-12-08 14:55
    关注

    You can try this:

    $(document).ready(function(){  
    
        $(".cb").on('click', function(e) {
        var count = 0;
        var list = $('.cb');
        
        $('.cb').each(function(i) {
            
          if($(this).is(':checked')) {
            count++;
          }
          
        });
        
        if(count > 2)
        {
            alert('You cannot check more than 2 checkboxes!');
            $(this).prop('checked', false);
          
          //return false;
        } else {
            return true;
        }
        
      });
    
    });  
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>
    
      <input class="cb" type="checkbox">Checkbox 1
      <br />
      <input class="cb" type="checkbox">Checkbox 2
      <br />
      <input class="cb" type="checkbox">Checkbox 3
      <br />
      <input class="cb" type="checkbox">Checkbox 4
    
    </div>

    Hope this helps!

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100