EchoFool Posted December 19, 2008 Share Posted December 19, 2008 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. Quote Link to comment Share on other sites More sharing options...
Psycho Posted December 19, 2008 Share Posted December 19, 2008 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> Quote Link to comment Share on other sites More sharing options...
EchoFool Posted December 20, 2008 Author Share Posted December 20, 2008 Thank you for the reply, the check all works with that new script thank you. How ever the uncheckall button does not? Is this because it called onClick="uncheckAll which no longer exists in the script or something? Quote Link to comment Share on other sites More sharing options...
Psycho Posted December 20, 2008 Share Posted December 20, 2008 You didn't read all of my last post! I stated you only need ONE function to perform the check all and the uncheck all. I provided the function and I modified the buttons to work with that one function. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.