开发者

Javascript -Check all Checkboxes problem

I'm using the javascript:

<SCRIPT LANGUAGE="JavaScript">
function Check(chk)
{
if(document.myform.CheckAll.value=="Check All"){
for (i = 0; i < chk.length; i++)
chk[i].checked = true ;
document.myform.CheckAll.value="Uncheck All";
} else {

for (i = 0; i < chk.length; i++)
chk[i].chec开发者_开发百科ked = false ;
document.myform.CheckAll.value="Check All";
}
}
</script>

On the html code:

<form name="myform" method="post" action="">
<input type="checkbox" name="check_list[]" value="<? echo $row['Report ID'] ?>">
<input type="checkbox" name="check_list[]" value="<? echo $row['Report ID'] ?>">
...*More Checkboxes*...
<input style="font-family: sans-serif; font-weight:bold; font-size:12px; border: 1px #000000 solid;" type="button" id="CheckAll" name="CheckAll" value="Check All"
onClick="Check(document.myform.check_list[])">

But it doesn't seem to be working...

It did work at some point, but that was before I used the name: "check_list[]" (the '[]' bit) -Does that cause a problem with the javascript? And if so how can I stop it? -Or how can I get the javascript to check all checkboxes? :)

Thank you very much.


Check this out (code duplication removed + improvements)

js:

function Check(frm){
    var checkBoxes = frm.elements['check_list[]'];
    for (i = 0; i < checkBoxes.length; i++){
        checkBoxes[i].checked = (frm.CheckAll.value == "Check All") ? 'checked' : '';
    }
    frm.CheckAll.value = (frm.CheckAll.value == "Check All") ? "Uncheck All" : 'Check All';
}

markup:

<form name="myform" method="post" action="">
<input type="checkbox" name="check_list[]" value="<? echo $row['Report ID'] ?>">
<input type="checkbox" name="check_list[]" value="<? echo $row['Report ID'] ?>">
<input style="font-family: sans-serif; font-weight:bold; font-size:12px; border: 1px #000000 solid;" type="button" id="CheckAll" name="CheckAll" value="Check All"
onClick="Check(document.myform)">

example: http://jsfiddle.net/steweb/XL6uh/


The "[ ]" characters a reserved in javascript to identify arrays. i.e. you can't reference them in the DOM using document.myform.check_list[]. This would refer to an array of elements named 'check_list'.

What you can do is retrieve the checkboxes from the form's element array instead. Just change your onclick like so:

onclick="Check(document.myform['check_list[]'])"

NB: I would recommend you learn a javascript framework such as jQuery. It makes doing this type of thing so much easier and you can write unobtrusive javascript.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜