jquery - How to run each loop on dynamically created items? -
in invoicing web application trying calculate item
totals of invoice
on client side jquery:
$(function() { // add together new row of item fields $('form.edit_invoice').on('click', '.add_fields', function(event) { var regexp, time; time = new date().gettime(); regexp = new regexp($(this).data('id'), 'g'); $(this).closest('tr').before($(this).data('fields').replace(regexp, time)); // replace id unique id calculateitemtotals(); event.preventdefault(); }); // update item total when item cost or quantity gets changed $('input[id$="_price"], input[id$="_quantity"]').on('change', function() { calculateitemtotals(); }); }); function calculateitemtotals() { $('.item_fields').each(function() { var cost = $(this).find('input[id$="_price"]').val(); var quantity = $(this).find('input[id$="_quantity"]').val(); var total = parsefloat(price) * parsefloat(quantity); $(this).find('.item_total').text(total); }); }
this works invoices items have been saved.
when creating new invoice, however, items added dynamically through jquery , above function doesn't work.
how can work items well?
thanks help.
update:
this link creates new invoice item:
<a class='add_fields icon_link new' data-fields='<tr class="item_fields"> <td width="13%" data-title="date"> <input class="item-datepicker" id="" type="text" value="20.10.2014" /><input id="invoice_items_attributes_2236275320_date" name="invoice[items_attributes][2236275320][date]" type="hidden" value="2014-10-20" /> </td> <td width="42%" data-title="description"> <input id="invoice_items_attributes_2236275320_description" name="invoice[items_attributes][2236275320][description]" type="text" value="erstellung einer website" /> </td> <td width="15%" data-title="price"> <input id="invoice_items_attributes_2236275320_price" min="0" name="invoice[items_attributes][2236275320][price]" type="number" value="50.0" /> </td> <td width="10%" data-title="qty"> <input id="invoice_items_attributes_2236275320_quantity" min="0" name="invoice[items_attributes][2236275320][quantity]" type="number" value="1" /> </td> <td width="10%" data-title="total"> <span class="item_total">0</span> </td> <td width="10%"> <input id="invoice_items_attributes_2236275320__destroy" name="invoice[items_attributes][2236275320][_destroy]" type="hidden" value="false" /> <a class="remove_fields icon_link destroy" href="#">remove</a> </td></tr>' data-id='2236275320' href='#'>add item</a>
it turns out standard (asked many times) problem dynamically created elements: dynamically created elements should utilize delegated event handlers .on():
$('form.edit_invoice').on('change', 'input[id$="_price"], input[id$="_quantity"]', function() { calculateitemtotals(); });
fiddle example.
jquery
No comments:
Post a Comment