开发者

JS, select all checkboxes within specific form, several forms on the page

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 开发者_JAVA技巧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>


<script type="text/javascript">
    function selectAll(val) {
        var checks = document.getElementsByName("selectfile[]");
        for (var i = 0; i < checks.length; i++) {
          checks[i].checked = val;
        }
    }
</script>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type='checkbox' name='checkall' style="margin-right: 15px;" onChange="selectAll(this.checked)">

<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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜