通过jquery检查所有复选框

时间:2014-04-17 09:27:41

标签: javascript jquery ruby-on-rails ruby-on-rails-4

我想在我的应用中通过jquery检查所有复选框。我有以下布局:

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

哪种方式最适合这件事?

6 个答案:

答案 0 :(得分:4)

试试这个

$(document).on('click','#selectAll',function () {
    $(this).closest('table').find('input[type=checkbox]').prop('checked', this.checked);
});

答案 1 :(得分:3)

$('#allcb').change(function () {
      $('tr td input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});

Demo:Fiddle

答案 2 :(得分:2)

要检查页面上的所有复选框,您可以使用:

 $("input:checkbox").attr("checked", "checked");

答案 3 :(得分:1)

试试这个脚本

$(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');
});
});    

并以您的表单/索引

<%= check_box_tag "locations[]", location.id %> 

答案 4 :(得分:1)

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

答案 5 :(得分:1)

嗨,只需给出一个简单的演示

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");

   });