How to do calculations in ajax div file?

I used an application using javascript to multiply the quantity by the price, but it only works on the first line.

Here is the controller:

def index
   @products= CustomerProduct.all
end 

def selected_product
   @selected_product = CustomerProduct.find(params[:id])
end

Here is the index view: (shows all products and updated div)

<% @products.each do |product| %>
 <p> 
    <%= product.product_name %>
    <%= link_to_remote image_tag("image.png"),:url=>{:controller=>"customer_product",:action=>"selected_product",:id=>product.id } %>
 </p>
<% end %>

<div id="list_products">
   ## Here is the div that will update after select a product.
</div> 

Here is an ajax update that will replace the div: "selected_product.rjs"

 page.insert_html(:bottom,"list_products", :partial=>"customer_product/partials/add_product")

Here is a partial view of add_product.erb displaying the selected information

<script type="text/javascript">
jQuery("#quantity").live("change", function(){
    quantity = parseFloat(jQuery(this).val() );
    importe = parseInt(jQuery("#importe").val());

    total2 = quantity*importe;   
    jQuery("#total2").val(total2.toFixed(2));
    jQuery("#total2").autoNumericSet(total2.toFixed(2));

  });
jQuery('input#total2').autoNumeric();
</script>

<% @products.each do |product| %>
 <p>
    <%= text_field_tag 'code',@selected_product.product_code,:maxlength=>"10",:size=>"10" if @selected_product %>
    <%= text_field_tag 'name',@selected_product.product_name,:size=>"40" if @selected_product %></td>
    <%= text_field_tag 'quantity',@net_insurance.to_i ,:value=>"1" ,:maxlength=>"9",:size=>"8" if @selected_product%>
    <%= text_field_tag 'importe',@selected_product.product_price ,:readonly=>true,:size=>"10" if @selected_product %>
    <%= text_field_tag 'total2',@total2.to_i,:maxlength=>"12",:size=>"12" if @selected_product %>
 </p>
<% end %>

It works fine only with the first line

enter image description here

But does not work after adding a few lines

enter image description here

It seems that javascript only works on the first line.

Please can anyone help me with this problem?

+4
source share
1 answer

, . , . HTML , , jQuery .

, - , ID. , .

:

jQuery(".quantity").live("change", function() {

    // find the parent <p> element of the quantity field
    var row = jQuery(this).parent();

    // retrieve the values from the fields in row
    quantity = parseFloat(jQuery(this).val());
    importe = parseInt(row.find(".importe").val());

    // do the calculation
    total2 = quantity * importe;

    // set the value to to the total2 field in row
    row.find(".total2").val(total2.toFixed(2));
    row.find(".total2").autoNumericSet(total2.toFixed(2));
});
+5

Source: https://habr.com/ru/post/1543162/


All Articles