jQuery - toggle select all checkboxes

前端 未结 3 1800
南旧
南旧 2020-12-05 14:27

Fought with a bunch of examples and, being still new to jQuery/Javascript, cannot get my code to function (here my my template in gsp):


    <         
相关标签:
3条回答
  • 2020-12-05 14:52

    Since you are using jQuery, you should use an onclick handler like below for selectAll.

    $(':checkbox[name=selectAll]').click (function () {
      $(':checkbox[name=domainList]').prop('checked', this.checked);
    });
    

    Please note that the above code is going to look into the entire dom for the checkbox with name=selectAll and set the status of the checkbox with name=domainList.

    Below is a slightly better version with minor markup change,

    jsFiddle DEMO

    $('#selectAllDomainList').click(function() {
      var checkedStatus = this.checked;
      $('#domainTable tbody tr').find('td:first :checkbox').each(function() {
        $(this).prop('checked', checkedStatus);
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <table id="domainTable">
      <!-- Added ID -->
      <thead>
        <tr>
          <th>
            <!-- Added ID to below select box -->
            <input type="checkbox" name="selectAll" id="selectAllDomainList" />
          </th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>
            <input type="checkbox" name="domainList" value="${domainInstance.id}" />
          </td>
        </tr>
        <tr>
          <td>
            <input type="checkbox" name="domainList" value="${domainInstance.id}" />
          </td>
        </tr>
        <tr>
          <td>
            <input type="checkbox" name="domainList" value="${domainInstance.id}" />
          </td>
        </tr>
        <tr>
          <td>
            <input type="checkbox" name="domainList" value="${domainInstance.id}" />
          </td>
        </tr>
      </tbody>
      <table>

    0 讨论(0)
  • 2020-12-05 14:58
    $("input:checkbox").prop("checked", status);
    
    0 讨论(0)
  • 2020-12-05 15:00

    to select all checkboxes with name = selectAll and set their status you can do

    function selectAll(status) {
       $('input[name=selectAll]').each(function(){
          $(this).prop('checked', status);
       });
    }
    
    0 讨论(0)
提交回复
热议问题