1

I want to check all checkboxes by jquery in my app. I have the following layout:

.row
    .col-md-12
      = field_set_tag t('car.places')
      %input{type: "checkbox", id: "selectAll"}/
      = t('car.select_all_locations')

      %table.table.table-striped.table-bordered.centered#car_locations
        %thead
          %tr
            %th{width: "200"}= t('cars.select')
            %th{width: "300"}= t('cars.your_locations')
            %th{width: "200"}= t('cars.location_type')
            %th{width: "400"}= t('cars.after_hours_availability')
        %tbody
          - Location.all.each do |location|
            %tr
              %td= check_box_tag "car[location_ids][]", location.id, @car.location_ids.include?(location.id), id: "test" 
              %td= location.name
              %td= location_type(location)
              %td= after_hours_availability(location)  

Which way is the best to to this thing?

Mateusz Urbański
  • 7,352
  • 15
  • 68
  • 133
  • possible duplicate of [How do I check a checkbox with jQuery?](http://stackoverflow.com/questions/426258/how-do-i-check-a-checkbox-with-jquery) – epoch Apr 17 '14 at 09:33

6 Answers6

4

Try this

$(document).on('click','#selectAll',function () {
    $(this).closest('table').find('input[type=checkbox]').prop('checked', this.checked);
});
Sridhar R
  • 20,190
  • 6
  • 38
  • 35
3
$('#allcb').change(function () {
      $('tr td input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});

Demo:Fiddle

Jignesh Rajput
  • 3,538
  • 30
  • 50
Richa Jain
  • 641
  • 6
  • 19
2

To check all the checkboxes on page, You can use:

 $("input:checkbox").attr("checked", "checked");
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

try this script

$(function) {
$('table th input:checkbox').on('click' , function(){
var that = this;
$(this).closest('table').find('tr > td:first-child input:checkbox')
.each(function(){
this.checked = that.checked;
$(this).closest('tr').toggleclass('selected');
});
});    

and in your form/index

<%= check_box_tag "locations[]", location.id %> 
Antony Mithun
  • 161
  • 1
  • 15
1

$('#selectAll').click -> if(this.checked) $(':checkbox').each -> this.checked = true else $(':checkbox').each -> this.checked = false

parliament
  • 67
  • 1
  • 8
1

Hi Just giving a simple demo for that

html

   <section>
     <ul id="ul1">
        <li><input type="checkbox" name="chk[]" id="chk1"/></li>
        <li><input type="checkbox" name="chk[]" id="chk2"/></li>
        <li><input type="checkbox" name="chk[]" id="chk3"/></li>
        <li><input type="checkbox" name="chk[]" id="chk4"/></li>
        <li><input type="checkbox" name="chk[]" id="chk5"/></li>
    </ul>
    <input type="button" name="bt1" id="bt2" value="check all"/>

</section>

js

   $("#bt2").on("click",function(){

    $("ul#ul1").find("input[type='checkbox']").attr("checked","checked");

   });
dinesh_malhotra
  • 1,829
  • 17
  • 10