js 세 모금

기여·2024년 6월 14일

소소한 개발팁

목록 보기
36/103

1, 숫자 천단위 콤마(쉼표) 찍기
'toLocaleString()' 이용하면 된다.

2, 구매량이 1 이상에서 0으로 줄었을 때 배송비도 0으로 반환

var pay = (pprice * amt) + (amt > 0 ? pdeliFee : 0);

3, 동일상품 구매시 해당 배송비는 한 번만 계산

for (var i = 0; i < pdeliFees.length; i++) {
		sumpay = sumpay + parseFloat(pdeliFees[i].value);
	}
	
	f1.totalPay.value = sumpay;

예제:

<script>
 function totalPay2() {
// 	alert("확인")
	var pprices = document.getElementsByName('pprice');
	var amts = document.getElementsByName('amt');
	var pdeliFees = document.getElementsByName('pdeliFee');
	var habs = document.getElementsByName('hab');
	var sumpay = 0;
	
	for (var i = 0; i < pprices.length; i++) {
		var amt = amts[i].value;
		var pprice = pprices[i].value;
		//동일상품 구매해도 pdeliFee 한 번만 계산
		var pdeliFee = parseFloat(pdeliFees[i].value);

		// 상품 가격 * 수량 + 배송비
		var pay = (pprice * amt) + (amt > 0 ? pdeliFee : 0); //amt = 0 인 경우 pdeliFee도 0
		habs[i].value = pay.toLocaleString(); // 합산 금액을 hab 필드에 설정
		sumpay += pay;
	}
	
	f1.totalPay.value = sumpay.toLocaleString();
}
 
 function allDel() {
	location.href="${path}/CartCtrl?sw=D";
}
 </script>
<form name=f1 action="${path}/CartCtrl">
 <input type="hidden" name=sw value="U">
 
 <table width=800>
<tr class=tr_color>
	<th>cartid</th>
	<th>pname</th>
	<th>pimg</th>	
	<th>pprice</th>
	<th>amt</th>
	<th>pdeliFee</th>
	<th>hab</th>
 </tr>

<c:if test="${li.size() == 0}">
	<tr><td colspan=7 align="center">주문내역 없음</td> </tr>
</c:if>
<c:if test="${li.size() != 0}">

	<c:forEach var="m" items="${li}">
	<c:set var="idx" value="${idx=idx+1}" />
	<tr class=tr_color align="center">
	<td> <input type="hidden" name=cartid value="${m.cartid}">  ${m.cartid}  </td>
	<td>  <a href="${path}/PrdCtrl?sw=E&pid=${m.pid}">${m.pname}</a>  </td> 
	<td align="center">
		<a href="${path}/PrdCtrl?sw=E&pid=${m.pid}">
		<img src=${path}/product/files/${m.pimg} width=70></a>
	</td> 
	<td> <input type="hidden" name="pprice" value="${m.pprice}"> 
	<fmt:formatNumber value="${m.pprice}" type="number" groupingUsed="true"/> </td> 
	
	<td> <input type="number" name="amt" value="${m.amt}"> </td> 
	
	<td> <input type="hidden" name="pdeliFee" value="${m.pdeliFee}"> 
	<fmt:formatNumber value="${m.pdeliFee}" type="number" groupingUsed="true"/> </td> 
	
	<td> <input type="text" name="hab" value="" readonly> </td> 
	</tr>
	</c:forEach>
	
	<tr class=tr_color> 
	<th colspan=7 align="right">예상금액: <input type="text" name="totalPay" readonly></th>
	</tr>
	
	<tr class=tr_color> 
	<td colspan=7 align="center"> 
	   <input class="button" type="button" value="예상금액 확인" onclick="totalPay2()">&emsp;
	   <!-- name="totalPay" 와 구분 -->
	   
	   <input class="button" type="button" value="주문하기">&emsp;
	   <input class="button" type="submit" value="변경저장">&emsp;
	   <input class="button" type="button" value="전체삭제" onclick="allDel()">
	   </td>
	</tr> 
	
</c:if>

</table>
</form>

결과:

profile
기기 좋아하는 여자

0개의 댓글