0

Hi i am currently using Collection_select like so , and as you can see its working properly but i want to make it, so that when i pick 1 item from the Item field that the data from my database , bought price and sold price would automatically be added into the textfields like in the example below.

but as to how i can do it, remains a mystery to me, can anybody help me with this and thanks! any help will be helpful! and thanks again!

enter image description here

the code that i used

<%= form_for(@sale) do |f| %>
  <% if @sale.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@sale.errors.count, "error") %> prohibited this sale from being saved:</h2>
      <ul>
      <% @sale.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :item_id %><br>
    <%= collection_select( :sale, :item_id, Item.all, :id, :name, {} ) %>
  </div>

  <div class="field">
    <%= f.label :bought %><br>
    <%= f.text_field :bought %>
  </div>
  <div class="field">
    <%= f.label :sold %><br>
    <%= f.text_field :sold %>
  </div>
  <div class="field">
    <%= f.label :number %><br>
    <%= f.number_field :number %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
user1868185
  • 899
  • 3
  • 9
  • 24

1 Answers1

1

you can do this by send ajax request and bought data from database then show "bought price" and "sold price" in there respective fields. Something like that

 $("#collection_select_id").change(function () {
  $.ajax({
    url: "your_url_where_you_get_your_data",
    method: "GET",
    data: {},
    success: function(data) {
     $("#bought_price_id").val(data.bought_price)
     $("#sold_price_id").val(data.sold_price)
    }
  });
});

Thanks

Qubaish Bhatti
  • 700
  • 5
  • 22
  • hi how do i send some ajax, sorry i am a bit new with rails – user1868185 Sep 08 '15 at 14:50
  • You can simply do this in your views file, like at the end of your view add "javascript" tag and then you can write your ajax request there. or follow this tutorial https://pragmaticstudio.com/blog/2015/3/18/rails-jquery-ajax. – Qubaish Bhatti Sep 09 '15 at 08:25