ユーザーがアイテム名、アイテム属性を選択し、アイテムの数量を入力する必要があるフォームがあります。ユーザーがさらに項目を必要とする場合、新しいフォームが複製されます。
特定の商品名の全数量の合計を計算したい。
使用事例:
- ユーザーはアイテム名
ABC
、属性を選択し、数量フィールドに入力します100
- 2 番目の「フォーム」(div コンテナー) で、 を選択
ABC
し、他の属性を選択して、数量を入力します。50
- 3 番目の「フォーム」(div コンテナー)
PQR
で、属性を選択し、数量を入力します。430
- 4 番目の「フォーム」(div コンテナー) で、 を選択
PQR
し、属性を選択し、数量を入力します。150
すべての PQR と ABC の合計を追加し、それぞれの入力フィールドに値を表示する必要があります。
私がこれまでに行ったこと:
$('.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>
このコードは合計を計算しますが、選択されたすべてのアイテムの合計を計算し、1 つの入力フィールドに表示します。選択したアイテム名に基づいて入力の合計を計算したいのですが、選択した各アイテム名の数量は、異なる入力フィールドに合計を表示する必要があります。たとえば、 (ABC
の合計は 1 つの入力フィールドに表示され、PQR
の合計は別の入力フィールドに表示されます。
どんな助けでも大歓迎です。