Skip to content

Instantly share code, notes, and snippets.

@iwan
Last active December 27, 2015 00:09
Show Gist options
  • Save iwan/7235873 to your computer and use it in GitHub Desktop.
Save iwan/7235873 to your computer and use it in GitHub Desktop.
Get multiple checkboxes in a index view

Routes file (routes.rb):

resources :data_loaders do
  collection do
    delete 'multiple_destroy'
  end
end

The controller:

# DELETE /data_loaders/multiple_destroy
# DELETE /data_loaders/multiple_destroy.json
def multiple_destroy
  @data_loaders = DataLoader.find(params[:ids])
  @data_loaders.each{ |dl| dl.destroy }

  respond_to do |format|
    format.html { redirect_to data_loaders_url }
    format.json { head :no_content }
  end
end

The view (index.html.haml):

= form_tag multiple_destroy_data_loaders_path, :method => :delete, :id => "ekko" do

  %table.table.table-striped.table-bordered.datatable
  %thead
      %tr
        %th= check_box_tag 'index-checkbox-all'
        ...

    %tbody
      - for data_loader in @data_loaders
        %tr
          %td= check_box_tag "ids[]", data_loader.id, false, :class => 'index-checkbox'
          ...

  = submit_tag t('.destroy'), :confirm => "Are you sure?", :class => "btn btn-danger", :id => "submit-multiple-destroy", :disabled => "disabled"

The javascript (a jQuery plugin):

(function ($) {
 
  $.fn.cb_batch_action = function(options) {
    // This is the easiest way to have default options.
    var f = this

    var settings = $.extend({
      // These are the defaults.
      submit_sel: "#submit-multiple-destroy",
      cb_sel: "input.index-checkbox",
      multi_cb_sel: "#index-checkbox-all"        
    }, options);

 
    count_checked = function() {
      return f.find(settings.cb_sel).filter(':checked').size();
    }

    submit_button = function(n) {
      var items;
      if (n>0) {
        f.find(settings.submit_sel).prop('disabled', false);
        items = (n>1) ? (n+" items?") : "1 item?";
        f.find(settings.submit_sel).attr('data-confirm', "Are you sure you want to destroy "+items);
      } else {
        f.find(settings.submit_sel).prop('disabled', true);
      };
    };

    $(settings.multi_cb_sel).click(function() {
      f.find(settings.cb_sel).prop('checked', $(this).is(':checked'));
      submit_button(count_checked());
    })

    $(settings.cb_sel).click(function() {
      var n = count_checked();
      submit_button(n);
      if (n==0) {
        f.find(settings.multi_cb_sel).prop('checked', false);
      }       
    })
  };


}( jQuery ));

$('#ekko').cb_batch_action();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment