jytoronto
jytoronto

Reputation: 558

Rails dynamically updated View based on user input

I'm trying to create a view page where the user enters the names of Item objects in a text field, or jquery token field (http://loopj.com/jquery-tokeninput/)

Each Item has a cost attribute, and I would like to display the total cost dynamicaly, without refreshing, whenever the user adds an item.

So at the top of the page there would be:

"Total Cost: $150", or "Total Cost: $120" if you remove an item that costs $30.

I feel it would be something involving javascript and AJAX but I'm not very proficient with it. Please advise, thanks!

Upvotes: 1

Views: 1030

Answers (2)

Rodrigo Zurek
Rodrigo Zurek

Reputation: 4575

Ok this is a complex question but i will try to help you as far as I can, I would sugest first of all adding that text field to a form, something like this:

show.html.erb:

<%= form_tag({:controller => "cart_items", :action => :create}, {:method => :post, :remote => true}) do %>                    
    <%= text_field_tag :product_name, product.name %>                          
<%end%>     

notice the :remote=> true to force rails to do an ajax call

after that in your controller you will need to handle that request so would be something like this:

def create     
    if @current_cart==nil
      @current_cart = Cart.create!
      @current_cart.save
      session[:cart] = @current_cart.id
    end
    @product = Product.find_by_name(params[:product_name])
    @current_cart.add(@product, @product.price)      
    respond_to do |format|
      format.js {redirect_to :back, :notice => "added"}
      format.html {redirect_to :back, :notice => "added"}
    end    
  end

after that you will need some javascript to handle that ajaxt response like this:

show.js.erb:

$('.cart').replaceWith('<%= j render :partial => "layouts/cart"%>');

the you need a cart parcial to replace:

layouts/_cart.html.erb:

<%@current_cart.each do |c| %>
 <%=c.product.name%>
<%end%>

im just scratching the surface on a quick answer but maybe you will find some direction cheers

Upvotes: 1

Spencer
Spencer

Reputation: 942

Would be interested in seeing the relevant view code, but in general you can just add things together to get the total.

If you need to get the value of a text field you can use .val() and to convert it to an int or a float you can use parseInt(string) or parseFloat(string)

Upvotes: 0

Related Questions