Coder_Nick
Coder_Nick

Reputation: 841

Ruby on Rails: Filling in form_for field depending on selection in other field

I have a Transaction model that handles the buying and selling of Stocks in a Portfolio. When determine which Stock I want to buy/sell I have a drop down using options_for_collection_for_select. Depending on which Stock Symbol I select, I want the buy_price field to fill in with the last_price associated with that Stock resource. Is there a way to store the selection from the f.select :stock_id and use it to autofill the buy_price field. Either with Rails or JavaScript.

<%= form_for([@portfolio, @transaction]) do |f| %>
  <% if @transaction.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@transaction.errors.count, "error") %> prohibited this transaction from being saved:</h2>

      <ul>
      <% @transaction.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :symbol %><br>
    <%= f.select :stock_id, options_from_collection_for_select(Stock.all, :id, :symbol), prompt: 'Please select a stock...' %>
  </div>
  <div class="field">
    <%= f.label :quantity %><br>
    <%= f.number_field :num_of_shares %>
  </div>
  <div class="field">
    <%= f.label :buy_price %><br>
    <%= f.number_field :buy_price %>
  </div>
  <div class="field">
    <%= f.label :buy_date %><br>
    <%= f.datetime_field :buy_date, :value => DateTime.now %>
  </div>

  <div class="actions">
    <%= f.submit class: 'btn btn-success' %>
  </div>
<% end %>

Upvotes: 0

Views: 333

Answers (1)

Ioana Surdu Bob
Ioana Surdu Bob

Reputation: 139

So, first you should give some class names to the fields you need to modify:

<%= f.select :stock_id, options_from_collection_for_select(Stock.all, :id, :symbol), prompt: 'Please select a stock...', {class: 'stock'} %>

<%= f.number_field :buy_price, class: "buyprice" %>

Then, to edit those fields you need to escape javascript many times, so what I used to change ruby variables was CDATA. My indentation might be wrong though (i've been using haml and i have to put tabs only inside ruby loops). You can't put a javascript variable inside escape javascript so you should make a loop and check for the value, then with it you change the value of the field you want to change. You could also make it read only or hidden, if you want the user not to change the input.

<script>
  \//<![CDATA[
  $(document).ready(function(){
  $(".stock").change(function(){
  stockval = $(this).val();
  <%- Stock.pluck(:id).each do |stock| %>
    if($(this).val() == "#{stock}") {
    $(".buyprice").val("#{Stock.find(stock).last_price)}");
    }
  <%- end %>
  });
  });
  \//]]>
</script>

I am not sure this is completely correct, but I hope this helps :).

Upvotes: 1

Related Questions