I got a page that contain X forms, in each form there is a number of checkboxes.
How do I make it so when I click on a checkbox (as displayed below), then all checkboxes in that specific form will be selected? (and un-selected if … un-checked):
I tried the following, but it does not work (name=”selectfile[]” must not be changed):
I’m not a JS king 🙁
function selectAll(){
t=document.forms[0].length;
for(i=1; i<t-1; i++) document.forms[0][i].checked=document.forms[0][0].checked;
}
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type='checkbox' name='checkall' style="margin-right: 15px;" onclick='selectAll(this.form.selectfile[]);'>
<input type="checkbox" name="selectfile[]" value="<? echo $file_fetch['id']; ?>" style="margin-right: 15px;" />
<input type="checkbox" name="selectfile[]" value="<? echo $file_fetch['id']; ?>" style="margin-right: 15px;" />
<input type="checkbox" name="selectfile[]" value="<? echo $file_fetch['id']; ?>" style="margin-right: 15px;" />
<input type="checkbox" name="selectfile[]" value="<? echo $file_fetch['id']; ?>" style="margin-right: 15px;" />
</form>
You can test the javascript part here: http://jsfiddle.net/protron/2t987/
Edit: Based on your comments about having multiple forms and all the checkboxes with the same name, I updated the code and added an extra parameter to the function indicating the form index, and then used
document.forms[formIndex]to get the checks. This seems to be the only easy way for this requirement without using jQuery, although IMHO it’s more error-prone this way.Code here: http://jsfiddle.net/protron/2t987/1/