Melvin
Melvin

Reputation: 376

Dynamically fetch a value based on drop down selection

I have a form with a drop-down menu that allows users to select how low they want to book an item. I am letting stripe to handle the payment. I would like to have the length retrieved dynamically based on the selection.

<%= form_tag pages_next_url(@booking), :length => params[:length] do %>

    <div class="input-field">
      <!--<%= label :length, "How long will you stay?" %>-->
      <%= select_tag "length", options_for_select(@garage_times.map { |obj| [obj['time'], obj['value']] }) %>
    </div>

    <%= hidden_field_tag :garageid, @garage.id %>

    <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
            data-key="<%= Rails.application.secrets.stripe_publishable_key %>"
            data-description="Payment"
            data-amount= <%= garage.weekday*100*length %> <-- need to get length (integer) dynamically 
            data-locale="auto"
            data-email= <%= current_user.email %> ></script>
<% end %>

In my controller, I have the values listed. When "1:00 hour" is selected, it should return length, 1 for this case, dynamically.

@garage_times = [
 {"value" => 1, "time" => "1:00 hour"},
 {"value" => 2, "time" => "2:00 hours"},
 {"value" => 3, "time" => "3:00 hours"},
 {"value" => 4, "time" => "4:00 hours"}
]

I understand that it requires AJAX/JS in order to retrieve the value dynamically. I did some research and watched Railscast on their dynamic form. However, it does not help on my case. All of the examples I have seen are retrieving values from a model. Also, I know that it can be done if I put the calculation in the controller, but the whole point is to allow users to see the total amount on the pay button when they input their payment information.

Please guide me. I have minimal knowledge of JS and AJAX. Thank you.

Edit: I am still unable to solve this problem still.

Upvotes: 0

Views: 177

Answers (1)

Shannon
Shannon

Reputation: 3018

It seems like you can avoid using AJAX and use the select list value. Then use the length value to update the button.

You can do something like this in jQuery:

$('#length').on('change', function() {
  weekday_rate = $('#weekday_rate').html();
  length = $(this).val();
  $('.stripe-button').attr('data-amount', weekday_rate * 100 * length)
})

Upvotes: 1

Related Questions