商品のオーダー画面で数を入力すると、合計をその場で表示したくてJQueryで。
input でname属性にitemid[]ではなくて、itemid[11]などとしているのは、post送信時に配列インデックスをidにして渡したかったから。
でもそれだとeachで扱えなかったので、かわりにclassにitemid[]をいれて対処。
| 品名 | 単価 | 数量 | 増やす | 減らす |
|---|---|---|---|---|
| クリームパン | 190 | |||
| カレーパン | 350 | |||
| アンパン | 320 | |||
| メロンパン | 230 | |||
| 合計 | 0円 |
jQuery(function( $ ) {
//+ボタンをクリックした時
$( 'tr.delivery td input.plus' ).on( 'click', function(){
var itemid = $(this).parents("tr").attr('itemid');
var count = $('tr.delivery td input#oder_itemid'+itemid).val();
if (count0){ count--; }
$('tr.delivery td input#oder_itemid'+itemid).val(count) ;
calTotal();
return false;
});
//合計の計算
function calTotal() {
var oderTotalPrice = 0;
var oderTotalNum = 0;
$( 'tr.delivery' ).each(function(i, val) {
$item =$(this).find('td .item_price');
var price = parseInt($(this).find('.item_price').html());
var num = $(this).find("input[class='itemid[]']").val();
oderTotalPrice += price * num;
oderTotalNum += num;
});
$( 'span#totalPrice' ).html(oderTotalPrice.toString());
}
//初めに表示した時に計算
calTotal();
});
| 品名 | 単価 | 数量 | 増やす | 減らす |
|---|---|---|---|---|
| クリームパン | 190 | |||
| カレーパン | 350 | |||
| アンパン | 320 | |||
| メロンパン | 230 | |||
| 合計 | 2190円 |