Mark Belli
Mark Belli

Reputation: 740

allow a minimum selection in a checkboxes limiting script

I have a javascript code that limits checkbox selection.

It's taking the number of checkboxes in a given page and allows only 30% of them to be selected.

This is the code:

function chkcontrol(j) {
  var length = document.forms['form1'].elements['item[]'].length;

  var max = Math.round(length * 0.3);
  var total = 0;
  for(var i = 0; i < length; i++){  
    if(document.forms['form1'].elements['item[]'][i].checked){
      total = total + 1;
    }
    if(total > max){
      alert("MAX 33%") ;
      document.forms['form1'].elements['item[]'][i].checked = false ;
      return false;
    }
  }
}

It works fine, but I would like to set an absolute minimum guaranteed number of checkboxes selectable.

In simple text, here is the rule I am trying to implement:

Example:

7 checkboxes in the page, only 2 allowed. (limit is 2, which is less than the minimum guaranteed of 5 --> the script should raise the limit to allow 5)

Any ideas how to do this? In php a simple IF condition would solve the problem, but I am not familiar with javascript!

Upvotes: 1

Views: 711

Answers (1)

Niko
Niko

Reputation: 26730

Why not go with something simple as this:

var max = Math.max(5, Math.round(length * 0.3));

max is the maximum of either 5 or the computed 30% - that way, max is never less than 5.

Upvotes: 2

Related Questions