[thelist] JS, counting selected checkboxes

jeff jeff at members.evolt.org
Sun Jan 21 18:54:31 CST 2001


aardvark,

:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
: From: aardvark
:
: i'm trying to find some JS that, on form
: submit or on selection of the 10th item,
: will notify the user that he/she has gone
: beyond the limit...
:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

i know you found a solution, but i find these sorts of questions fun, so i
thought i'd respond anyway.

in order for this to work you'll need to store the number of items checked
as well as the pre-defined limit.  then, as items are checked you increment
the count or as items are unchecked you decrement the count.  if the count
surpasses the limit then you throw an alert and set the checkbox back to
unchecked.  here's how i'd handle it:

put this in the <head> of your document:

<script language="JavaScript" type="text/javascript">
<!--
  var numberChecked = 0;
  var maxAllowed = 10;

  function limitChecked(obj)
  {
    numberChecked = (obj.checked) ? numberChecked++ : numberChecked--;
    if(numberChecked > maxAllowed)
    {
      alert('You may only check up to '
           + maxAllowed
           + ' items.');
      obj.checked = false;
      numberChecked--;
    }
  }
// -->
</script>

and then attach the following event handler to any checkbox you wish to have
this limitation:

onClick="limitChecked(this)"

good luck,

.jeff

name://jeff.howden
game://web.development
http://www.evolt.org/
mailto:jeff at members.evolt.org





More information about the thelist mailing list