0

I am using the following sample HTML code below. With jQuery, I am unsure how to implement a "Select/Deselect All" using the id="select-all" to check / uncheck all the below checkboxes where name="p_v01"

<span style="font-size:8px;">Select All</span><br>&nbsp;
<input type="checkbox" name="select-all" id="select-all">
<span style="font-weight:bold;font-size:16px;padding-left:20px;">Emps</span>
<table summary="" role="presentation" class="checkbox_group">
  <tbody>
   <tr>
    <td>
     <input type="checkbox" id="P2_EMP_CB_0" name="p_v01" value="ANALYST">
     <label for="P2_EMP_CB_0">ANALYST</label>
    </td>
    <td>
     <input type="checkbox" id="P2_EMP_CB_1" name="p_v01" value="CLERK">
     <label for="P2_EMP_CB_1">CLERK</label>
    </td>
    <td>
     <input type="checkbox" id="P2_EMP_CB_2" name="p_v01" value="MANAGER">
     <label for="P2_EMP_CB_2">MANAGER</label>
    </td>
    <td>
     <input type="checkbox" id="P2_EMP_CB_3" name="p_v01" value="PRESIDENT">
     <label for="P2_EMP_CB_3">PRESIDENT</label>
   </td>
   <td>
    <input type="checkbox" id="P2_EMP_CB_4" name="p_v01" value="SALESMAN">
    <label for="P2_EMP_CB_4">SALESMAN</label>
  </td>
 </tr>
</tbody>

halfer
  • 19,824
  • 17
  • 99
  • 186
tonyf
  • 34,479
  • 49
  • 157
  • 246

3 Answers3

2

You can use:

$('#select-all').click(function() {
    $('input[name="p_v01"]').prop('checked',this.checked);    
});

Fiddle Demo

Felix
  • 37,892
  • 8
  • 43
  • 55
  • this will not work if user checks/unchecks the checkbox using keyboard – Ejaz May 12 '14 at 10:34
  • @Felix : I have found an Issue with your Demo..if you select all then unchecked any option like(ANALYST, CLERK, Manager, etc) then select all must be unchecked... here is the [Solution](http://stackoverflow.com/questions/24630578/select-deselect-all-dynamic-checkboxes-in-rails-4-with-javascript/24630833?noredirect=1#answer-24632567) – Gagan Gami Jul 08 '14 at 14:15
1

Try this:

$('#select-all').on('change', function() {
   $('input[name="p_v01"]').prop('checked', this.checked);    
});

  1. Have a change event on #select-all
  2. Find the input by name with attribute selector $('input[name="p_v01"]')
  3. every time when you check/uncheck it results in true/false.
Jai
  • 74,255
  • 12
  • 74
  • 103
0

Use below jQuery

<script>
 $(document).ready(function(){
   $('#select-all').click(function(){
      $('input[name="p_v01"]').attr("checked",$(this).is(':checked'));
   });

});
</script>
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57