Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails, select and deselect all checkboxes

I have a button and when I click on it, I want all checkboxes to be selected. By clicking the second time, all checkboxes must be deselected.

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

Something does not work here. Can you help me please?

edit:

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

does not alert anything

in 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

in 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' %>
like image 857
Alina Avatar asked Nov 17 '14 16:11

Alina


2 Answers

U tried to call the "click" event on the element "check_all" before it gets loaded. Hence only the alert function doesnt work.

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

For selecting the checkboxes,

$(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);
     }
   });
});
like image 56
Orchid Avatar answered Oct 20 '22 00:10

Orchid


Try this:

$('#check_all').on("click", function(){
  var cbxs = $('input[type="checkbox"]');
  cbxs.prop("checked", !cbxs.prop("checked"));
});
like image 36
jljohnstone Avatar answered Oct 20 '22 01:10

jljohnstone