Jump to content

[SOLVED] Checkall not working


EchoFool

Recommended Posts

I have a js script to check all checkbox's in a form but it won't work i keep getting an error on my debugger which is:

 

field is undefined

[break on this error] for (i = 0; i < field.length; i++)

 

My JS is:

 

function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}

function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}

 

Any my form:

 

<form method="post" name="myform" action="deletemail.php">
<?php
foreach( $array as $key => $value ){
?>

<input type="checkbox" name="list[]" value="<?=$value?>">

<?php
}
?>

<input type="submit" name="Submit" value="Delete!">
<br><br>

<input type="button" name="CheckAll" value="Check All" onClick="checkAll(document.myform.list)">

<input type="button" name="UnCheckAll" value="Uncheck All" onClick="uncheckAll(document.myform.list)">

</form>

 

Where have i gone wrong? Hope you can help me out.

Link to comment
Share on other sites

Using "list[]" for a field name creates an array such as $_POST['list'] (no brackets) in PHP

 

But JavaScript sees it as an array with the name "list[]" (with brackets). So you will need to reference it like this:

document.myform['list[]']

 

Also, you only need ONE function for both operations. Just pass a true/false parameter for the checked value:

 

function checkAll(fieldSet, checked)
{
    for (var i=0; i<fieldSet.length; i++)
    {
fieldSet[i].checked = checked;
    }
}

 

<form method="post" name="myform" action="deletemail.php">
<?php
foreach( $array as $key => $value ){
?>

<input type="checkbox" name="list[]" value="<?=$value?>">

<?php
}
?>

<input type="submit" name="Submit" value="Delete!">
<br><br>

<input type="button" name="CheckAll" value="Check All" onClick="checkAll(document.myform['list[]'], true)">

<input type="button" name="UnCheckAll" value="Uncheck All" onClick="uncheckAll(document.myform['list[]'], false)">

</form>

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.