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

时间:2014-11-17 16:11:59

标签: jquery ruby-on-rails checkbox

我有一个按钮,当我点击它时,我希望选中所有复选框。通过第二次单击,必须取消选中所有复选框。

  <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' %>

2 个答案:

答案 0 :(得分:7)

你试图在加载元素“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);
     }
   });
});

答案 1 :(得分:3)

试试这个:

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