I have a form in which the user has to select the item name, item attributes and enter the item quantity. A new form is cloned if the user wants more items.
I want to calculate the sum of all quantities of specific item name.
Use Case:
- The user chooses item name
ABC
, attributes and enters in the quantity field100
- In the second "form" (div container), selects
ABC
, selects other attributes and enters quantity50
- In the third "form" (div container) selects
PQR
, attributes, enters quantity430
- In the 4th "form" (div container) selects
PQR
, chooses attributes, enters quantity150
I need to add the sum of all PQR and ABC and display value in their respective input fields.
What I have done so far:
$('.quantity-input').on('blur', function() {
getTotalQuantity();
});
function getTotalQuantity() {
var $qr = $('.quantity-input');
var sum = 0;
var item_name;
$qr.each(function(i, obj) {
var self = $(this);
item_name = self.closest(".abc-form").find('.select-item-name').val();
item_name = item_name.replace(/\s/g, '').toLowerCase();
console.log(item_name);
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
var input_item_name = $('input[data-item-name="' + item_name + '" ]');
if (input_item_name.length) {
input_item_name.val(sum);
} else {
$('.add-item-quantity').append('<p><input type="text" value="' + sum + '" class="' + item_name + '" data-item-name="' + item_name + '"/></p>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="abc-form">
<select class="select-item-name">
<option>ABC</option>
<option>PQR</option>
<option>XYZ</option>
</select>
<input type="text" class="quantity-input">
</div>
<div class="abc-form">
<select class="select-item-name">
<option>ABC</option>
<option>PQR</option>
<option>XYZ</option>
</select>
<input type="text" class="quantity-input">
</div>
<div class="abc-form">
<select class="select-item-name">
<option>ABC</option>
<option>PQR</option>
<option>XYZ</option>
</select>
<input type="text" class="quantity-input">
</div>
<div class="abc-form">
<select class="select-item-name">
<option>ABC</option>
<option>PQR</option>
<option>XYZ</option>
</select>
<input type="text" class="quantity-input">
</div>
<div class="add-item-quantity">
</div>
While this code calculates the sum, it calculates the sum of all selected items and shows in one input field. I want to calculate the sum of the inputs based on item names selected and each selected item name's quantity should show the sum in a different input field. For eg (ABC
's sum will display in one input field, while PQR
's sum will display in another input field.
Any help would be appreciated.