Sunday 18 September 2016

Checkbox tag with kaminari pagination



If you are using kaminari pagination with ajax and using check-box tag for selecting product there may be a problem in selection of product from different page because of pagination ajax it will select only products of last page.

In this situation, we can use jquery for updating the selected products.

In view page -
Here we have created a view of product listing with check-box tag and ajax pagination -


    <div class="product_list">
      <% if products.size > 0 %>
          <% products.each do |product| %>
              <div class="form-group">
                <%= check_box_tag "products[]", product.id, false, class: 'selected_product' -%>
                <%= image_tag(product.image_url, class: "list_pro_img") %>
                <%= link_to product.item_title, product.item_url, target: '_blank' %>
              </div>
          <% end %>
      <% else %>
          <p>Product is not found</p>
      <% end %>
    </div>
    <div id="paginator">
      <%= paginate @products, :remote => true %>
    </div>
    <%= submit_tag "Next", :class => "btn btn_next selected_post_product" %> 

Now we will update all the selected product from different page in products global variable of jquery -

So in custom.js -

function post_selected_products(){


    if (!Array.prototype.remove) {
        Array.prototype.remove = function(val, all) {
            var i, removedItems = [];
            if (all) {
                for(i = this.length; i--;){
                    if (this[i] === val) removedItems.push(this.splice(i, 1));
                }
            }
            else {
                i = this.indexOf(val);
                if(i>-1) removedItems = this.splice(i, 1);
            }
            return removedItems;
        };
    }

# In the above jquery we are removing items from array if product was unchecked after checked.
    products = [];
    $('div.product_list').on('change','input.selected_product',function(){
        if($(this).is(':checked')){
            var product_id = $(this).val();
            products.push(product_id)
        }else{
            var product_id = $(this).val();
            products.remove(product_id)
        }
# Now, we will post all the selected product on products controller -
        $.post('/products/selected_products', { product_ids: products});
    });



In view include above js -


<script type="text/javascript" charset="utf-8">
    post_selected_products()
</script>


In products controller -


def selected_products
    if request.xhr?
      # Here we will get all the selected products
      @products = params[:product_ids]
    end
end


Thats it !!!

No comments:

Post a Comment