Rails 5, Ajax, jQuery - increase number when button clicked -
if user clicks "add cart" button, need increase number 1 in navbar div, show how many products in cart.
so, button has remote: true
set
and navbar has div id count.
function use increase number:
$('#count').html(function(i, val) { return val*1+1 });
but if reload page value disappears. how can make value stay there until action, 'checkout'?
or maybe there better way this?
create model method or helper method user finding count of active cart items. provides accurate value too.
for example:
class user < applicationrecord has_many :cart_items def active_cart_items return self.cart_items.group_by(&:product_id).count #.where(status:active) (optional) end end
create ur_action.js.erb
under ur_controller
in set items in cart counter
$('#count').html("<%=@user.active_cart_items%>")
Comments
Post a Comment