简体   繁体   中英

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:

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.

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.

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;
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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