SEJU
SEJU

Reputation: 1125

Rails select form: displaying and using select form value before submit?

I am working on a multi step form for an order placement process. In it I have two selectors for shipping countries and shipping services. After selecting the country all shipping services are displayed for a given place and weight. When the order is placed everything is written to the model. All the shipping details process is done through a multistep form following Ryan Bates #217 Multistep Forms

The shipping service selector is populated through a javascript ajax call after the shipping country has been chosen. I followed this two tutorials Dynamic select boxes with Rails 4 and Dependent country city state.

$(document).on("change", "#lands_select", function(event){
  $.ajax({
    url: "/carts/update_shipping/" + event.target.value,
    type: "GET"
  })
});

update_shipping.js.erb

$("#shippingservices_select").empty()
  .append("<%= escape_javascript(render(:partial => @shippingservices)) %>");

_shippingservice.html.erb

<option value="<%= shippingservice.id %>"><%= shippingservice.name.titleize %></option>

In addition to this I would like to display the shipping cost related to the selection made in both selectors below the form together with the calculated total shipping cost.

The subtotal cost of the cart is calculated in the cart model and for the order in the order model.

How can I do this? Since both values have not been written to the order database yet I would have to display the resulting price of the second selector selection which is inside the shipping services table, but since the order has bot been written yet I cannot call it through the order instance variable. My guess is that I would have to do this adapting the ajax call, could that be? How would I have to do this?

What I have now is that the form is populated through json produced by the order controller's update_shipping action as far as I understand.

Thanks in advance!

Upvotes: 1

Views: 465

Answers (1)

Vasfed
Vasfed

Reputation: 18444

You can pass that column in data attributes:

<option value="<%= shippingservice.id %>" data-cost="<%= shippingservice.cost %>"><%= shippingservice.name.titleize %></option>

and then display via JS like

$(document).on("change", "#shippingservices_select", function(event){
  var cost = $(event.target).data('cost');
  $("#some_cost_div").html(cost);
  // maybe add to total etc.
});

Upvotes: 2

Related Questions