Come posso implementare una casella di controllo "Seleziona tutto" nel mio ASP.NET MVC app?

voti
9

Ho una tabella con una colonna piena di caselle di controllo. In cima mi piacerebbe avere un unico Seleziona tutto casella di controllo che avrebbe visualizzate tutte le caselle di controllo su quella pagina.

Come dovrei implementare questo? Sto utilizzando jQuery come il mio framework JavaScript se è importante.

È pubblicato 31/07/2009 alle 18:42
fonte dall'utente
In altre lingue...                            


7 risposte

voti
4

jquery ( EDITED per alternare controllo / deselezionare tutte):

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

Il motivo per cui ho dovuto fare un click()quindi controllare checkedlo stato è perché se si tenta di " toggle" una casella di controllo, la casella di controllo viene attivata non manterrà il suo status di controllato. In questo modo si mantiene lo stato di controllo ed efficace alterna.

HTML:

<input type="checkbox" id="toggleAll" />
<div id="chex">
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
</div>
Risposto il 31/07/2009 a 18:46
fonte dall'utente

voti
0

KingNestor:

Anche lei avrà bisogno di questo link (se non l'avete già scoperto):

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

Risposto il 31/07/2009 a 19:00
fonte dall'utente

voti
1

Mentre le risposte postato in precedenza funzioneranno, si incorrerà in problemi se si dispone di più di un set di caselle di controllo in una singola pagina.

Questo formato funziona a prescindere:

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

e lo script ...

$(function() {
    $('th > :checkbox').click(function() {
        $(this).closest('table')
            .find('td > :checkbox')
            .attr('checked', $(this).is(':checked'));
    });
});
Risposto il 31/07/2009 a 19:56
fonte dall'utente

voti
1

Modificando leggermente markup dalla risposta di Marve (dando ID alla tabella)

Working Demo →

MODIFICARE:

Aggiornamento versione in cui la casella di controllo 'selectAll' riflette correttamente lo stato delle caselle di controllo. Ad esempio, se si seleziona manualmente tutte le caselle, casella selectAll otterrà automaticamente controllato. Provate la demo per capire il comportamento.

Codice:

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

Il tuo jQuery potrebbe essere semplice come questo:

$(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);
            }
        );
    }
 );
Risposto il 31/07/2009 a 20:05
fonte dall'utente

voti
10

Ciò manterrà tutte le singole caselle di controllo lo stesso di quello "controllare tutti"

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

Ciò manterrà il "check" uno in sincronia con se o non le singole caselle di controllo sono in realtà tutti controllati 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);
    }
});
Risposto il 01/08/2009 a 07:49
fonte dall'utente

voti
0

Prova questo per tabella 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>  

script:

 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;  
   } 
Risposto il 23/10/2014 a 11:06
fonte dall'utente

voti
0

Per me, la soluzione di Jeremy per lo più lavorato, ma ho dovuto sostituire .attr con .prop. In caso contrario, una volta che ho singolo cliccato su una casella di controllo che avrebbe smesso di reagire alla casella di controllo "master".

nella (pagina master) _Layout.cshtml

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

in cui si fa riferimento .js

    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);
        }
    });
}

nella pagina 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: anche, in un primo momento ho avuto un @foreachciclo nel codice HTML e non ha funzionato ..., è necessario utilizzare un @for (int i = 0; i < Model.Clients.Count(); i++)ciclo al posto altrimenti si finisce con una lista vuota in OnPostAsync().

Risposto il 06/08/2019 a 23:32
fonte dall'utente

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