자바스크립트 합계구하기

자바스크립트 합계구하기

QA

자바스크립트 합계구하기

본문

<script>
function addPrice() {
 totalPrice = 0;

 for(i=0; i<fwrite.price.length; i++) {
  {
   totalPrice = fwrite.price[i].value * fwrite.price[i].itemname;
  }
 }

 document.getElementById('hap').value = comma(totalPrice);
 document.getElementById('to_price').innerText = comma(parseInt(totalPrice) + (parseInt(totalPrice)/10));
 document.getElementById('총결제비용').value = parseInt(totalPrice) + (parseInt(totalPrice)/10); 
}

 

=================================================================

자바스크립트로 합계내는 소스인데..

합계가 나오니 않고, NaN 이렇게 나옵니다.



function comma(num) {
 num = num.toString();
 len = num.length;
 str = "";
 for(i=1; i<=len; i++) {
  str = num.charAt(len-i)+str;
  if((i%3 == 0)&&(len-i != 0)) str = ","+str;
 }
 return str+"원";
}
</script>

[중략]

<form name="fwrite" method="post" onsubmit="return fwrite_submit(this);" enctype="multipart/form-data" style="margin:0px;">

     <table width="100%" align=center cellpadding=0 cellspacing=0>
       <tr>
         <td class="title1">항목 1 / 가  격: 20원</b></td>
         <td class="content1">수 량: 
               <input type=text  id="price" name="wr_11" onblur="addPrice()" size="5" maxlength="5" id="wr_11"  itemname="20"  value="<?=$write[wr_11]?>"></td>
        </tr>
        <tr>
         <td class="title1">항복2 / 가  격: 30원</b></td>
         <td class="content1">수 량: 

            <input type=text  id="price" name="wr_12" onblur="addPrice()" size="5"  maxlength="5" id="wr_12"  itemname="30"  value="<?=$write[wr_12]?>"></td>

.

.

.

.

<tr>
  <td class="title">합계금액</td>
  <td><input type=text itemname="hap" id="hap" size="15"  maxlength="10" name="wr_39" value="<?=$write[wr_39]?>" readonly> </font></td>
</tr>

 <tr>
    <td class="title">총 결제 비용</td>
    <td class="content"><span id="to_price">0</span> 원 (부가세가 포함된 금액입니다.)
   <input type='hidden' maxlength=50 size=30% id="총결제비용" name="wr_40" itemname="총결제비용"  value="<?=$write[wr_40]?>">
 </td>
 </tr>

</form>
============================================================================

자바스크립트로 합계내는 건데...

 

input 의 value값이 수량이고, itemname이 단가입니다.

 

totalPrice = 수량(input 값) x 단가(itemname) 값이고,
이 값들을 for 문으로 합산해서 총합계 hap 으로 계산되야 되는데...

값이 표시되지 않고. NaN 이렇게 나오는데...

무엇이 문제인지 못찾고 있습니다.

 

도움주시면 감사하겠습니다. ^^;; 

이 질문에 댓글 쓰기 :

답변 4

일단 id가 두개네요

id="price"를 클래스로 변경하시고

 

가격 구하는 함수를 변경하시면 됩니다. 


 
function addPrice() {
 totalPrice = 0;
    
$(".price").each(function(){
    totalPrice += Number($(this).val()) * Number($(this).attr("itemname"));
});
 document.getElementById('hap').value = comma(totalPrice);
 document.getElementById('to_price').innerText = comma(parseInt(totalPrice) + (parseInt(totalPrice)/10));
 document.getElementById('총결제비용').value = parseInt(totalPrice) + (parseInt(totalPrice)/10); 
} 
 
<input type=text  class="price" name="wr_11" onblur="addPrice()" size="5" maxlength="5" id="wr_11"  itemname="20"  value=""> 
 

function addPrice() {
 var totalPrice = 0;
 var price = document.getElementsByClassName('price');
 for(i=0; i<price.length; i++) {
  {
			totalPrice += Number(price[i].value) * Number(price[i].getAttribute('itemname'));
  }
 }
 document.getElementById('hap').value = comma(totalPrice); 
 document.getElementById('to_price').innerText = comma(parseInt(totalPrice) + (parseInt(totalPrice)/10));
 document.getElementById('총결제비용').value = parseInt(totalPrice) + (parseInt(totalPrice)/10); 
}

 

일단 jquery는 잘 모르는 것 같아서 님 수준에 맞게 수정해본거구요. id는 중복해서 쓰면 안됩니다.

그래서 가격 입력받는곳에

<input type=text name="wr_12" onblur="addPrice()" size="5"  maxlength="5" id="wr_12"  itemname="30"  value="<?=$write[wr_12]?>" class='price'> 이런식으로 class를 같게 맞춰줍니다. 그리고 님 html 보면 input에 id가 두번 선언되어있어요.



function addPrice() {
 var totalPrice = 0;
 $('.price').each(function() {
	totalPrice += Number($(this).val()) * Number($(this).attr("itemname"));
 });
 
 $('#hap').val(comma(totalPrice)); 
 $('#to_price').val(comma(Number(totalPrice) + (Number(totalPrice)/10)));
}
이건 jQuery로 짠거고 

    <td class="title">총 결제 비용</td>
    <td class="content"><input type='text' maxlength=50 size=30% id="to_price" name="wr_40" itemname="to_price"  value="<?=$write[wr_40]?>" style='border:0; text-align:right' readonly> 원 (부가세가 포함된 금액입니다.)
총합부분도 span으로 찍어주는것으로 해놨는데 그럴필요가 없어요. input에 border 값 없애고 우측 정렬하면 input인지 티가 안남 readonly 속성때문에 수정 안되구요
답변을 작성하시기 전에 로그인 해주세요.
전체 27
QA 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT