¿Cómo puedo implementar una casilla de verificación "Seleccionar todo" en mi aplicación ASP.NET MVC?

votos
9

Tengo una mesa con una columna llena de casillas de verificación. En la parte superior, me gustaría tener una sola casilla de verificación Seleccionar todo que verificaría todas las casillas de verificación en esa página.

¿Cómo debo implementar esto? Estoy usando jQuery como mi marco de JavaScript si es que importa.

Publicado el 31/07/2009 a las 18:42
fuente por usuario
En otros idiomas...                            


7 respuestas

votos
4

jquery ( EDITADO para alternar marcar / desmarcar todo):

$(document).ready(function() {
    $("#toggleAll").click(function() {  
      $("#chex :checkbox").attr("checked", $(this).attr("checked"));
    });    
});

La razón por la que tuve que hacer una click()comprobación de checkedestado luego es porque si intentas marcar " toggle" una casilla de verificación, la casilla de verificación que se está alternando no conservará su estado verificado. De esta forma, conserva el estado de verificación y alterna de forma efectiva.

HTML:

<input type="checkbox" id="toggleAll" />
<div id="chex">
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
</div>
Respondida el 31/07/2009 a las 18:46
fuente por usuario

votos
0

KingNestor:

También necesitará este enlace (si aún no lo ha descubierto):

http: //www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysLists ...

Respondida el 31/07/2009 a las 19:00
fuente por usuario

votos
1

Si bien las respuestas publicadas anteriormente funcionarán, se encontrará con problemas si tiene más de un conjunto de casillas de verificación en una sola página.

Este formato funcionará independientemente:

<table>
    <thead>
        <tr>
            <th><input type="checkbox" /></th>
            <th>Column 1</th>
            <th>Column 2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" /></td>
            <td>Tabular Data 1</td>
            <td>Tabular Data 2</td>
        </tr>
        <tr>
            <td><input type="checkbox" /></td>
            <td>Tabular Data 3</td>
            <td>Tabular Data 4</td>
        </tr>
    </tbody>
</table>

y el guion ...

$(function() {
    $('th > :checkbox').click(function() {
        $(this).closest('table')
            .find('td > :checkbox')
            .attr('checked', $(this).is(':checked'));
    });
});
Respondida el 31/07/2009 a las 19:56
fuente por usuario

votos
1

Marcado ligeramente modificado de la respuesta de Marve (dando ID a la mesa)

Demo de trabajo →

EDITAR:

Versión actualizada donde la casilla 'selectAll' refleja correctamente el estado de las casillas de verificación. Por ejemplo, si selecciona todas las casillas de verificación manualmente, seleccione Todas las casillas de verificación se verificarán automáticamente. Pruebe la demostración para comprender el comportamiento.

Código:

<table id='myTable'>
    <thead>
        <tr>
            <th><input type="checkbox" /></th>
            <th>Column 1</th>
            <th>Column 2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" /></td>
            <td>Tabular Data 1</td>
            <td>Tabular Data 2</td>
        </tr>
        <tr>
            <td><input type="checkbox" /></td>
            <td>Tabular Data 3</td>
            <td>Tabular Data 4</td>
        </tr>
    </tbody>
</table>

Tu jQuery podría ser tan simple como esto:

$(document).ready(
    function()
    {
        $('#myTable th input:checkbox').click(
            function() 
            {
                $('#myTable td input:checkbox').attr('checked', $(this).attr('checked'));
            }
        );

        //The following code keeps the 'selectAll' checkbox in sync with
        //the manual selection of the checkboxes by user. This is an additional usability feature.
        $('#myTable tr input:checkbox').click(
            function()
            {
                var checkedCount = $('#myTable td input:checkbox:checked').length;
                var totalCount = $('#myTable td input:checkbox').length;
                $('#myTable th input:checkbox').attr('checked', checkedCount === totalCount);
            }
        );
    }
 );
Respondida el 31/07/2009 a las 20:05
fuente por usuario

votos
10

Esto mantendrá todas las casillas de verificación individuales de la misma manera que las "marque todas"

$("#id-of-checkall-checkbox").click(function() {
    $(".class-on-my-checkboxes").attr('checked', this.checked);
});

Esto mantendrá el "verificar todos" sincronizado con si las casillas de verificación individuales están todas marcadas o no

$(".class-on-my-checkboxes").click(function() {
    if (!this.checked) {
        $("#id-of-checkall-checkbox").attr('checked', false);
    }
    else if ($(".class-on-my-checkboxes").length == $(".class-on-my-checkboxes:checked").length) {
        $("#id-of-checkall-checkbox").attr('checked', true);
    }
});
Respondida el 01/08/2009 a las 07:49
fuente por usuario

votos
0

Para probar esta tabla HTML.

<table class="rptcontenttext" style="width: 100%; border-style: solid; border-collapse: collapse"  
         border="1px" cellpadding="0" cellspacing="0">  
         <thead>  
           <tr>  
             <th style="text-align:left;width:10px;">  
             <input type="checkbox" value="true" name="chkVerifySelection" id="chkVerifySelection" onchange="return     checkAllVerifySelection();" />  
             </th>  
             <td class="rptrowdata" align="left">  
               Employee ID  
             </td>  
           </tr>  
         </thead>  
         <tbody style="overflow-y: auto; overflow-x: hidden; max-height: 400px; width: 100%;">  
             @for (int i = 0; i < Model.EmployeeInformationList.Count; i++)  
             {      
           <tr>  
             <td style="width:10px">    
               @{  
               if (Model.EmployeeInformationList[i].SelectStatus==true)  
                 {  
                 @Html.CheckBoxFor(model => model.EmployeeInformationList[i].SelectStatus, new { @class = "VerifyStatus" ,disabled =                  "disabled",@checked="checked" })   
                 }  
                 else  
                    {  
                   @Html.CheckBoxFor(model => model.EmployeeInformationList[i].SelectStatus, new { @class = "VerifyStatus" })   
                    }  
                 }        
            </td>             
             <td class="rptrowdata" align="left" style="width: 70px">  

               @Html.Encode(Model.EmployeeInformationList[i].StrEmpID)   

             </td>  
              <td class="rptrowdata" align="center" style="width: 50px">  
               @Html.HiddenFor(m=>m.EmployeeInformationList[i].strEmpOldCardNo)  
                @Html.Encode(Model.EmployeeInformationList[i].strEmpOldCardNo)  
             </td>  
           </tr>  
             }  
         </tbody>  
       </table>  

Guión:

 function checkAllVerifySelection() {  
     var flag = $('input[name=chkVerifySelection]').is(':checked');  
     if (flag) {  
       $(".VerifyStatus").each(function () {  
         $(this).attr('checked', true);  
       });  
     }  
     else {  
       $(".VerifyStatus").each(function () {  
         $(this).attr('checked', false);  
       });  
     }  
     return true;  
   } 
Respondida el 23/10/2014 a las 11:06
fuente por usuario

votos
0

Para mí, la solución de Jeremy sobre todo trabajado, pero tenía que reemplazar .attr con .prop. De lo contrario, una vez que sola hace clic en una casilla de verificación que dejaría de reaccionar a la casilla de verificación "maestro".

en el (página principal) _Layout.cshtml

$(document).ready(
    manageCheckboxGroup('chkAffectCheckboxGroup', 'checkbox-group')
);

en un Js referenciados

    function manageCheckboxGroup(masterCheckboxId, slaveCheckboxesClass) {

    $("#" + masterCheckboxId).click(function () {
        $("." + slaveCheckboxesClass).prop('checked', this.checked);
    });

    $("." + slaveCheckboxesClass).click(function () {
        if (!this.checked) {
            $("#" + masterCheckboxId).prop('checked', false);
        }
        else if ($("." + slaveCheckboxesClass).length == $("." + slaveCheckboxesClass + ":checked").length) {
            $("#" + masterCheckboxId).prop('checked', true);
        }
    });
}

en la página HTML (Razor)

<table class="table">
    <thead>
        <tr>
            <th><input id="chkAffectCheckboxGroup" type="checkbox" checked="checked" /></th>
            <th>
                @Html.DisplayNameFor(model => model.Clients[0].ClientId)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Clients[0].Name)
            </th>
        </tr>
    </thead>
    <tbody>
        @for (int i = 0; i < Model.Clients.Count(); i++)
        {
            <tr>
                <td>
                    <input type="hidden" asp-for="Clients[i].Id" class="form-control" />
                    <input type="hidden" asp-for="Clients[i].Name" />
                    <input type="checkbox" class="checkbox-group" asp-for="Clients[i].Selected" />
                </td>
                <td>
                    @Html.DisplayFor(modelItem => Model.Clients[i].Id)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => Model.Clients[i].Name)
                </td>
            </tr>
        }
    </tbody>
</table>

IMPORTANTE: También, al principio tuve un @foreachbucle en el HTML y no funcionó ..., debe utilizar un @for (int i = 0; i < Model.Clients.Count(); i++)bucle en lugar de lo contrario se termina con una lista vacía en el OnPostAsync().

Respondida el 06/08/2019 a las 23:32
fuente por usuario

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more