bharath
bharath

Reputation: 623

nested form collection_select new value overwriting previous selected values

Nested form

<%= nested_form_for(@bill) do |f| %>

<p><%= f.link_to_add "Add Product", :bill_line_items %> </p>

Partial of bill line items

<%= javascript_include_tag 'bill'%>

<%= f.hidden_field :bill_id %>

<%- prices = Hash[Product.all.map{|p| [p.id, p.price]}].to_json %>

<%= f.label :product_id %>
<%= f.collection_select :product_id ,Product.all,:id,:name, :class => 'product',  :prompt => "Select a Product", input_html: {data: {prices: prices}}%> <br/ >


<%= f.label :price, "price"%> 
<%= f.text_field :price, :size=>20, :class =>"price" %><br/>

bill.js

jQuery(document).ready(function(){
        jQuery('.product').change(function() {
            var product_id = jQuery(this).val();
            var price = eval(jQuery(this).data("prices"))[product_id];
            jQuery('.price').val(price);
        });
    });

Rails 3.2 Issue: Second click on Add Product & on selecting the product When we select the second product the price of second product is overwriting on the price of the first selected product. Request help.

Upvotes: 1

Views: 317

Answers (1)

deeraj
deeraj

Reputation: 148

This is the solution I have arrived at. I believe this is a very bad way to do it But it gets the work done.

jQuery(document).ready(function(){
  jQuery("customer-outer").delegate("select", "change", function(event){
    var selectElement = jQuery(this);
    var productId = selectElement.val();
    var price = eval(selectElement.data('prices'))[productId];
    var lineItemWrapperElement = selectElement.parent().parent();
    jQuery("input.price", lineItemWrapperElement).val(price);
  });
});

customer-outer is class of div defined new.html and edit.html. If anyone finds a proper solution for this, please do share.

Upvotes: 1

Related Questions