简体   繁体   中英

How to select all boxes using input type checkbox

picture of my columns and checboxes

<table class="table table-striped grid-table">
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>
        <input type="checkbox" id="box"/>
        </th>
    </tr>
    @foreach (var item in (IEnumerable<cit.Models.getPersonPerName_Result>)Model)
    {
        <tr>
            <td>@item.idper</td>
            <td>@item.pername</td>
            <td>      

             <div class="pure-checkbox">
               <input type="checkbox" id="@item.idper" class="chk" checked="@(item.idperson == ViewBag.idperson ? true : false)" name="@item.id.ToString()" id="@item.id.ToString()" />
               <label for="@item.id.ToString()"></label>
             </div>

            </td>
        </tr>
    }

I have defined class pure-checkbox , so item.idper is my column with values of my document, and item.pername is my column with codes of my document, and there is pure-checkbox column which I defined for checkboxes which i can check only one by one, but i want to check them all using input type on the code above.

The way to to this is to listen for changes in the state of the 'master' checkbox. You can do this by attaching an event handler. When this handler is triggered you have to set the checked state of all other checkboxes to the checked state of the 'master' checkbox:

var selectAllBox = document.getElementById('box');
selectAllBox.addEventListener('click', function() {
    var pureCheckboxes = document.getElementsByClassName('chk');
  
  for(var i = 0; i < pureCheckboxes.length; i++) {
    pureCheckboxes[i].checked = this.checked;
  }
});

A working JSFiddle: https://jsfiddle.net/TDucheyne/raxdzw1f/

You can do it with a single line as

$(document).ready(function(){
  $("#box").change(function(){  
    $(".chk").prop('checked',$(this).prop('checked'));
  });
});

JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM