Hướng dẫn xử lý js trang cart, khi change số lượng, thành tiền, tổng tiền change theo

Đăng bởi Quách Gia Luân

Khi có sản phẩm trong trang giỏ hàng, nếu như tăng giá trị số lượng sản phẩm lên, thì tăng thành tiền và tổng tiền sản phẩm lên. Để làm được điều đó, ta có thể làm theo cách sau:

Bước 1: Mở file Cart.liquid và tìm đến đoạn code hiển thị thành tiền và thêm vào thuộc tính id:
<td class="price" id="line_price_{{ item.id }}">{{ item.line_price | money }}</td>

Thêm đoạn code sau vào trước đoạn có

class="qty"

:

<td class="price" id="price_{{ item.id }}">{{ item.price | money}}</td>
Sau đó thêm 1 dòng td sau vào trclass="summary" :
<td>&nbsp;</td>

Thêm id vào đoạn code: 

<span class="total">
	<strong id="total">{{ cart.total_price | money }}</strong>
</span>

Sau đó xuống cuối cùng thêm vào đoạn script sau:


<script>
var arrays = {};
window.onload = function () {
	var inputs = document.getElementsByTagName('input');
	for (var i = 0; i < inputs.length; i++) {
		var input_id,quantity;
		if (inputs[i].id.indexOf('updates_') != -1) {
			input_id = inputs[i].id.replace('updates_','');//lấy id của input
			arrays[input_id] = document.getElementById('price_' + input_id).innerHTML.replace(/₫|,/g,'');
			inputs[i].onchange = function () {
				input_id = this.id.replace('updates_','');//lấy id của input
				var price = document.getElementById('price_' + input_id).innerHTML.replace(/₫|,/g,'');
				var line_total_price = 0;
				quantity = document.getElementById('updates_' + input_id).value;
				if(quantity != ""){
					line_total_price += parseInt(quantity)*price;
				}
				line_total_price = line_total_price.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
				document.getElementById('line_price_'+input_id).innerHTML = line_total_price + "₫";

				//tổng tiền
				var total = 0;
				for(var array in arrays){
					quantity = document.getElementById('updates_' + array).value;
					if(quantity != ""){
						total += parseInt(quantity)*arrays[array];
					}
				}
				total = total.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
				document.getElementById('total').innerHTML = total + "₫";
			}
		}
	}
}
</script>

Ý nghĩa của đoạn code này:

  • Tìm các thẻ input, sau đó kiểm tra các thẻ input thỏa điều kiện.
  • Tìm id của input và id của giá tiền sản phẩm.
  • Khi mà input thay đổi thì thành tiền của sản phẩm sẽ thay đổi theo và tổng tiền của các sản phẩm cũng thay đổi theo.

Hoàn thành. Chúc các bạn thành công.

Link demo: http://hrvcom.myharavan.com/?themeid=1000059616

Bạn là lập trình viên? Gia nhập gia đình haravan Chi tiết ›