Checkbox Display and Detection (Javascript):   Return to List

<SCRIPT LANGUAGE="JavaScript">
<!--
function whichIsIt(frm)
{
    var chkBx = "";
    for(i=0; i<frm.check.length; i++)
    {
        if(frm.check[i].checked == true)
        {
            chkBx += "Checkbox " + i + " is checked.\n"
        }
    }
    alert(chkBx);
}

/* *************************************************

' You could also build the function as follows:
' it declares an array to store a list of which boxes are checked
' it loops through the checkboxes and adds the index of each checked box to the new array
' the new array's length property is used as the index of each new entry, ensuring that they are added to the end of the array
' finally, a custom output message is build, depending on how many boxes are checked

function whichIsIt(frm)
{
    var chkBx = new Array(); // define array to hold reference to checked boxes

    // determine which checkboxes are checked and store their number in the array
    for(i=0; i<frm.check.length; i++)
    {
        if(frm.check[i].checked==true)
        {
            chkBx[chkBx.length] = i;
        }
    }

    // build an output message
    if(chkBx.length > 1)
    {
        alert("Checkboxes " + chkBx + " are checked.");
    }
    else if(chkBx.length == 1)
    {
        alert("Only checkbox " + chkBx + " is checked.");
    }
    else
    {
        alert("No checkboxes are checked.");
    }
}
******************************************* */

//-->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="simpleFrm">
Yes: <INPUT TYPE="checkbox" NAME="check" CHECKED>
No: <INPUT TYPE="checkbox" NAME="check">
Maybe: <INPUT TYPE="checkbox" NAME="check">
<BR><BR>
<INPUT TYPE="button" VALUE="Which is checked?" onClick="whichIsIt(this.form)">
</FORM>
</BODY>



Note to Webmaster