[Javascript] Checkbox challenge

Chris T christ at saeweb.com
Thu May 6 15:24:42 CDT 2004


Are all of these checkboxes in the same group of checkboxes? If so, you
don't need to loop through the form as below, but rather like this:

var numChecked = 0
var objForm = document.forms["FormName"]
var objEl = objForm.elements["CheckboxNames"]

for(var x = 0; x < objEl.length; x++){
    if(objEl[x].checked){
        numChecked++
    }
}

Then you could use the same validation on the number checked that Shawn has
shown you, but if this script applies to just the one element, then the
below script could fail if other checkboxes are on the form.

It's the same premise as Shawn's script, just more specific.

Chris Tifer
http://emailajoke.com



----- Original Message ----- 
From: "Shawn Milo" <milo at linuxmail.org>
To: "[JavaScript List]" <javascript at LaTech.edu>
Sent: Thursday, May 06, 2004 3:53 PM
Subject: Re: [Javascript] Checkbox challenge


> Try some modification of this:
>
> In each checkbox:  onclick="threeOnly(this)"
>
> function threeOnly(lastChecked){
>
>    var numChecked = 0;
>
>    for (x=0;x<document.forms[0].elements.length;x++){
>       if ((document.forms[0].elements[x].type == 'checkbox') &&
(document.forms[0].elements[x].value == 'on')){
>          numChecked++;
>       }
>    }
>
>    if (numChecked > 3){
>       lastChecked.checked = false;
>       alert('Please uncheck another option before choosing this one.  You
may select a maxumim of three');
>    }
>
> }
>
>
>
> Note:
>
> Untested, and I sometimes get confused about how you refer to the status
of a
> checkbox between ASP and Javascript, so my syntax may be screwy, but
here's
> something I think you can work with.
>
> Shawn
> _______________________________________________
> Javascript mailing list
> Javascript at LaTech.edu
> https://lists.LaTech.edu/mailman/listinfo/javascript




More information about the Javascript mailing list