javascript - How can do calculations in ajax update div? -
i did application using javascript multiply quantity price working first row.
here controller:
def index @products= customerproduct.all end def selected_product @selected_product = customerproduct.find(params[:id]) end
here index view: (is showing products , div update)
<% @products.each |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 div update after select product. </div>
here ajax update replace div: "selected_product.rjs"
page.insert_html(:bottom,"list_products", :partial=>"customer_product/partials/add_product")
here partial view add_product.erb, showing information selected
<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 |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 %>
is working fine first row
but not working after adding more rows
seems javascript working first row.
please can me problem?
the problem here accessing fields using ids. ids the same on every product row. valid html, id of every element must unique, , that's reason jquery selectors picking first row.
to solve issue, either generate unique ids each row, or use other ids. classes, example.
here's modified version of change handler use classes:
jquery(".quantity").live("change", function() { // find parent <p> element of quantity field var row = jquery(this).parent(); // retrieve values fields in row quantity = parsefloat(jquery(this).val()); importe = parseint(row.find(".importe").val()); // calculation total2 = quantity * importe; // set value to total2 field in row row.find(".total2").val(total2.tofixed(2)); row.find(".total2").autonumericset(total2.tofixed(2)); });
Comments
Post a Comment