Jump to content

[SOLVED] Checking all checkboxes


adam84

Recommended Posts

I want to loop through all the checkboxes and check or uncheck each of the city box. But whe n the JS selAll function gets called, I always get an error that says

"Error: document.cityFRM.city has no properties".

 

Any Ideas?

 

Javascript

function selAll( check ){
    alert( document.cityFRM.city.length );
}

 

 

HTML


<FORM NAME='cityFRM' ID='cityFRM' METHOD=GET ACTION='city.php'>

         <INPUT TYPE=CHECKBOX ONCLICK='javascript:selAll(this.checked);'>Check All<BR>

        <INPUT TYPE=CHECKBOX VALUE='New York' NAME='city[]' ID='city[]'>New York
        <INPUT TYPE=CHECKBOX VALUE='Chicago' NAME='city[]' ID='city[]'>Chicago
        <INPUT TYPE=CHECKBOX VALUE='Los Angeles' NAME='city[]' ID='city[]'>Los Angeles
        <INPUT TYPE=CHECKBOX VALUE='Detroit' NAME='city[]' ID='city[]'>Detroit
</FORM>

 

*I need to keep the the checkbox name an array, "city[]". I just want to know how to loop through them.

Link to comment
https://forums.phpfreaks.com/topic/119600-solved-checking-all-checkboxes/
Share on other sites

Using square brakets in that manner creates an array obect with that name (minus the brackets) when the form is received by a PHP page, but javascript does not look at it that way. To javascript is creates an array with that name - including the brackets!

 

function selAll( check ){
    alert( document.cityFRM['city[]'].length );
}

<html>
<head>

<script type="text/javascript">

function selectAll(checkBool)
{
    checkAry = document.cityFRM['city[]'];
    for (var i=0; i<checkAry.length; i++)
    {
        checkAry[i].checked = checkBool;
    }
    return true;
}

function selOne(checkBool)
{
    selAllObj = document.getElementById('selAll');
    if (!checkBool) { selAllObj.checked = false; }
    return true;
}

</script>

</head>

<body>


<form name="cityFRM" id="cityFRM" METHOD=GET ACTION="city.php">
    <input type="checkbox" onclick="selectAll(this.checked);" id="selAll">Check All<BR>
    <input type="checkbox" onclick="selOne(this.checked);" value="New York" name="city[]" id="city[]">New York
    <input type="checkbox" onclick="selOne(this.checked);" value="Chicago" name="city[]" id="city[]">Chicago
    <input type="checkbox" onclick="selOne(this.checked);" value="Los Angeles" name="city[]" id="city[]">Los Angeles
    <input type="checkbox" onclick="selOne(this.checked);" value="Detroit" name="city[]" id="city[]">Detroit
</form>



</body>
</html>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.