Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

checkbox - jQuery - toggle select all checkboxes

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

<table>
    <thead>
    <tr>
       <th><input type="checkbox" name="selectAll" onclick="selectAll(this.checked);"/></th>
    </tr>
    </thead>
    <tbody>
         <td>
            <td><input type="checkbox" name="domainList" value="${domainInstance.id}"/></td>
    </tbody>
<table>

I have the following javascript snippet in my main gsp, that calls the template:

function selectAll(status) {

}

How do I select all checkboxes from the selectAll name?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...