Pregunta

Tengo una lista de checkox con un par de artículos y una opción Todo. El usuario puede seleccionar todo y quiero que esto marque todas las opciones y si desmarcan todo, desmarcará todas las opciones.

He logrado esto con el siguiente código.

<script language="javascript" type="text/javascript">
    function CheckBoxListSelect(cbControl) //, state)
    {
        var chkBoxList = document.getElementById(cbControl);
        var chkBoxCount= chkBoxList.getElementsByTagName("input");

        alert(chkBoxCount[0].checked);

        for(var i=0;i<chkBoxCount.length;i++)
        {   
            chkBoxCount[i].checked = chkBoxCount[0].checked //state;
        }

        return false; 
    }
</script>

cblAffiliation.Attributes.Add("onclick", "javascript: CheckBoxListSelect ('" & cblAffiliation.ClientID & "');")

El problema es que si selecciono alguno de los cuadros, los boques y luego los establece en cualquiera que sea toda la opción. Tengo problemas para descubrir la mejor manera de evitar esto.

Quiero evitar usar una casilla de verificación junto a la lista de cheques, luego tengo que hacer esa línea con la lista de cheques.

¿Fue útil?

Solución

Simplemente marque para ver si el cuadro hizo clic era la opción Todo. Si fue así, adelante y cambie el resto de las cajas. Si no es así, verifique todas las opciones para ver si están todos marcados para que pueda actualizar la casilla de verificación 'All'.


EDITAR

Es posible que desee usar OnChange, en lugar de OnClick, OnClick probablemente se llamará antes de que se cambie el valor en la casilla de verificación dada.


Código no marcado, perdone los problemas de sintaxis.

<script language="javascript" type="text/javascript">
    function CheckBoxListSelect(cbControl) //, state)
    {
        var chkBoxList = document.getElementById(cbControl);
        var chkBoxCount= chkBoxList.getElementsByTagName("input");
        var clicked = this;

        alert(chkBoxCount[0].checked ? 'All is Checked' : 'All is not Checked');
        alert(clicked == chkBoxCount[0] ? 'You Clicked All' : 'You Didn't click All');

        var AllChecked = true; // Check the all box if all the options are now checked

        for(var i = 1;i < chkBoxCount.length; i++)
        {   
            if(clicked == chkBoxCount[0]) { // Was the 'All' checkbox clicked?
                chkBoxCount[i].checked = chkBoxCount[0].checked; // Set if so
            }
            AllChecked &= chkBoxCount[i].checked; // AllChecked is anded with the current box
        }

        chkBoxCount[0].checked = AllChecked;

        return false; 
    }
</script>

cblAffiliation.Attributes.Add("onchange", "javascript: CheckBoxListSelect ('" & cblAffiliation.ClientID & "');")

Otros consejos

 <asp:CheckBox ID="checkAll" runat="server" Text="Select/Unselect" onclick="CheckAll();" />
    <asp:CheckBoxList ID="chkTest" runat="server" onclick="ClearAll();">
        <asp:ListItem Text="Test 1" Value="0"></asp:ListItem>
        <asp:ListItem Text="Test 2" Value="1"></asp:ListItem>
        <asp:ListItem Text="Test 3" Value="2"></asp:ListItem>
            </asp:CheckBoxList>
<script type="text/javascript">

function CheckAll() {
    var intIndex = 0;
    var rowCount=document.getElementById('chkTest').getElementsByTagName("input").length;
    for (intIndex = 0; intIndex < rowCount; intIndex++) 
    {
        if (document.getElementById('checkAll').checked == true)
        {
            if (document.getElementById("chkTest" + "_" + intIndex)) 
            {
                if (document.getElementById("chkTest" + "_" + intIndex).disabled != true)
                    document.getElementById("chkTest" + "_" + intIndex).checked = true;
            }
         }
         else
         {
             if (document.getElementById("chkTest" + "_" + intIndex)) 
                {
                    if (document.getElementById("chkTest" + "_" + intIndex).disabled != true)
                        document.getElementById("chkTest" + "_" + intIndex).checked = false;
                }
         }
    }
 } 

function ClearAll(){
    var intIndex = 0;
    var flag = 0;
    var rowCount=document.getElementById('chkTest').getElementsByTagName("input").length;
    for (intIndex = 0; intIndex < rowCount; intIndex++) 
    {
            if (document.getElementById("chkTest" + "_" + intIndex)) 
            {
                    if(document.getElementById("chkTest" + "_" + intIndex).checked == true)
                    {
                        flag=1;
                    }
                    else
                    {
                        flag=0;
                        break;
                    }
            }
    }
    if(flag==0)
         document.getElementById('checkAll').checked = false;
    else
         document.getElementById('checkAll').checked = true;

}
</script>

Creo que este código te ayudará.

<script type="text/javascript">
function check(checkbox) 
{
 var cbl = document.getElementById('<%=CheckBoxList2.ClientID %>').getElementsByTagName("input");
 for(i = 0; i < cbl.length;i++) cbl[i].checked = checkbox.checked;
}
</script>

 <asp:CheckBox ID="CheckBox1" runat="server" onclick="check(this)" />
 <asp:CheckBoxList ID="CheckBoxList2" runat="server">
    <asp:ListItem>C1</asp:ListItem>
    <asp:ListItem>C2</asp:ListItem>
  </asp:CheckBoxList>

 function checkparent(id) {
            var parentid = id;
            var Control = document.getElementById(parentid).getElementsByTagName("input");
            if (parentid.indexOf("List") != -1) {
                parentid = parentid.replace("List", "");
            }
            if (eval(Control).length > 0) {
                if (eval(Control)) {

                    for (var i = 0; i < Control.length; i++) {
                        checkParent = false;
                        if (Control[i].checked == true) {
                            checkChild = true;
                        }
                        else {

                            checkChild = false;
                            break;
                        }
                    }
                }
            }
            if (checkParent == true && document.getElementById(parentid).checked == false) {
                document.getElementById(parentid).checked = false;
                checkParent = true;
            }
            else if (checkParent == true && document.getElementById(parentid).checked == true) {
                document.getElementById(parentid).checked = true;
                checkParent = true;
            }
            if (checkChild == true && checkParent == false) {
                document.getElementById(parentid).checked = true;
                checkParent = true;
            }
            else if (checkChild == false && checkParent == false) {
                document.getElementById(parentid).checked = false;
                checkParent = true;
            }

        }
        function CheckDynamic(chkid) {
            id = chkid.id;
            var chk = $("#" + id + ":checked").length;
            var child = id + "List";
            if (chk != 0) {
                $("[id*=" + child + "] input").attr("checked", "checked");
            }
            else {
                $("[id*=" + child + "] input").removeAttr("checked");
            }
            checkparent(id);
        }

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top