简体   繁体   English

动态限制可选复选框的最大数量

[英]Dynamically limit maximum number of checkboxes selectable

I found many scripts to limit max number of checkboxes that can be selected in a page with javascript, for example here is one: 我发现许多脚本限制了可以在使用javascript的页面中选择的复选框的最大数量,例如,以下是其中之一:

http://www.plus2net.com/javascript_tutorial/checkbox-limit.php http://www.plus2net.com/javascript_tutorial/checkbox-limit.php

However I don't need a specific number, but a VARIABLE one. 但是我不需要一个特定的数字,而是一个可变的数字。

This means that I need to have a percentage limit instead of just a number. 这意味着我需要有一个百分比限制,而不是一个数字。

For example, limit user selection to max 30% of the checkboxes in the page. 例如,将用户选择限制为页面中复选框的最大30%。

Any help on how to achieve this is highly appreciated! 非常感谢您对如何实现这一目标的任何帮助!

To alter that script to be a percentage vs. a fixed total you just need to take 30% of the total number of elements. 要将脚本更改为相对于固定总数的百分比,您只需要占用元素总数的30%。

function chkcontrol(j) {
  var length = document.form1.chb.length;

  // Max number allowed checked is 30% of the total
  var max = Math.round(length * .3);
  var total = 0;
  for(var i = 0; i < length; i++){
    if(document.form1.ckb[i].checked){
      total = total + 1;
    }

    if(total > max){
      alert("Please Select only three") 
      document.form1.ckb[j].checked = false ;
      return false;
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM