Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

javascript: Unchecking all checkboxes

I have problem dealing with unchecking all checkboxes. When I click on a toggle all checkbox, it could check all checkboxes. But if I uncheck the toggle all checkbox, nothing happens. All checkboxes are not unchecked. Below is my coding in javascript:

<script>
var isAllCheck = false;
function togglecheckboxes(cn){

    var cbarray = document.getElementsByName(cn);
    for(var i = 0; i < cbarray.length; i++){

        if( isAllCheck == false ){
            cbarray[i].checked = "true";
            //alert( "it is false" );
        }else{ 
            cbarray[i].removeAttribute("checked");
            //alert( "it is true" );
        }
}   
isAllCheck = !isAllCheck;   
}
</script>

I had even tried this coding, but still failed:

<script>
var isAllCheck = false;
function togglecheckboxes(cn){

    var cbarray = document.getElementsByName(cn);
    for(var i = 0; i < cbarray.length; i++){

        if( isAllCheck == false ){
            cbarray[i].checked = "true";
            //alert( "it is false" );
        }else{ 
            cbarray[i].checked = "false";
            //alert( "it is true" );
        }
}   
isAllCheck = !isAllCheck;   
}
</script>

Below is my PHP coding for your reference:

echo "<div class='item'>
<span class='CDTitle'>{$cd['CDTitle']}</span>
<span class='CDYear'>{$cd['CDYear']}</span>
<span class='catDesc'>{$cd['catDesc']}</span>
<span class='CDPrice'>{$cd['CDPrice']}</span>
<span class='chosen'><input type='checkbox' name='cd[]' value='{$cd['CDID']}' title='{$cd['CDPrice']}' /></span>
</div>
";

Any tips on resolving this problem. Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem boils down to how you're setting the checked property of the checkox. You're assigning a string with "true" where you should be assigning the boolean value true.

So to fix your code is easy:

if( isAllCheck == false ){
    cbarray[i].checked = true;
}else{ 
    cbarray[i].checked = false;
}

or, more succinctly

cbarray[i].checked = !isAllCheck

Live example: http://jsfiddle.net/SEJZP/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...