Ruby on Rails,选择和取消选择所有复选框

8
我有一个按钮,当我点击它时,我希望所有复选框都被选中。再次点击时,所有复选框必须取消选择。
  <script type='text/javascript'>
   $('#check_all').on("click", function(){ $('input[type="checkbox"]').click(); });
   </script>



<%= form_tag save_share_patients_clinicdb_grp_pats_path, method: :post do %>

<%= hidden_field_tag 'to_share_group', @to_shr_group%>
<button type="button" id="check_all" class="btw"><%="Check all/Uncheck all"%></button>

    <%@pat_ids.each do |pat_id|
    %>  
        <%= check_box_tag "to_share_patients[]", pat_id.mk1%> <%=pat_id.mk1%>
        <br/>
    <%end%>

<%= button_tag :class => "btn btn-warning", :name => 'share' do %> <%= t "share" %> <% end %> 
<%end%> 

这里有些问题。你能帮我吗? 编辑:
 $('#check_all').on("click", function(){ alert("aaa"); });

没有任何警报提示

在application.js中:

//= require jquery
//= require jquery_ujs
//= require jquery.Jcrop
//= require jquery.purr
//= require jquery-fileupload
//= require best_in_place
//= require rails.validations
//= require_self
//= require_tree ./bootstrap
//= require_tree ./jquery
//= require_tree ./menu
//= require_tree ./notifications
//= require_tree ./search
//= require_tree ./sort
//= require dataTables/jquery.dataTables

在 application.html 中。
<%= javascript_include_tag 'jquery.min', 'jquery-ui-1.10.4.custom.min.js' %>
<%= stylesheet_link_tag    "/assets/ui-lightness/jquery-ui-1.10.4.custom" %>
<%= javascript_include_tag 'application' %>

你的页面中是否包含了jQuery库? - jljohnstone
@jljohnstone 不是,我该怎么包含它? - Alina
使用 jquery-rails gem:https://github.com/rails/jquery-rails,但它应该已经默认包含在你的 Rails 项目中。也许你从 app/assets/javascripts/application.js 文件中删除了它。 - jljohnstone
Gemfile 中有 'jquery-rails',application.js 中有 //= require jquery 和 //= require jquery_ujs,但仍然无法正常工作。 - Alina
你是否在应用程序布局文件(app/views/layouts/application.html.erb)中包含了你的JavaScript,像这样:<%= javascript_include_tag 'application' %> - jljohnstone
1
@jljohnstone 我试过了,但它仍然不起作用。 - Alina
2个回答

11

在"check_all"元素加载之前,您尝试调用"click"事件。因此,只有警报功能无法正常工作。

$(document).ready(function(){
   $('#check_all').on("click", function(){ alert("hi") });
});

选择复选框,

$(document).ready(function(){
   $('#check_all').on("click", function() {
     // grouping all the checkbox using the classname
     var checkboxes = $("class name for the checkbox");
     // check whether checkboxes are selected.
     if(checkboxes.prop("checked")){
        // if they are selected, unchecking all the checkbox
        checkboxes.prop("checked",false);
     } else {
        // if they are not selected, checking all the checkbox
        checkboxes.prop("checked",true);
     }
   });
});

5

试试这个:

$('#check_all').on("click", function(){
  var cbxs = $('input[type="checkbox"]');
  cbxs.prop("checked", !cbxs.prop("checked"));
});

必须添加$( function() { })。 - Alina
1
“cbxs”? 真的吗?你可以直接拼写成“复选框”。 - Alexander
1
你刚刚颠倒了所有的复选框。对于所要求的功能,你必须像 @Orchid 一样单独检查每个复选框的状态。 - Nikita Kobtsev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接