Reputation: 7882
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?
Upvotes: 1
Views: 120
Reputation: 641
$('#allcb').change(function () {
$('tr td input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});
Upvotes: 3
Reputation: 1877
Hi Just giving a simple demo for that
<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>
$("#bt2").on("click",function(){
$("ul#ul1").find("input[type='checkbox']").attr("checked","checked");
});
Upvotes: 1
Reputation: 67
$('#selectAll').click ->
if(this.checked)
$(':checkbox').each ->
this.checked = true
else
$(':checkbox').each ->
this.checked = false
Upvotes: 1
Reputation: 161
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 %>
Upvotes: 1
Reputation: 82241
To check all the checkboxes on page, You can use:
$("input:checkbox").attr("checked", "checked");
Upvotes: 2
Reputation: 20428
Try this
$(document).on('click','#selectAll',function () {
$(this).closest('table').find('input[type=checkbox]').prop('checked', this.checked);
});
Upvotes: 4