2010-05-08 5 views
2

jquery에서이 작업을 수행하는 방법을 알아 낸 것입니다. 플러그인 없이도이 작업을 수행해야합니다. 도서 장바구니를 상상해보십시오. 수량을 변경할 때마다 (선택 드롭 다운 사용) 총액, 총액 및 숨겨진 입력 값이 업데이트됩니다.jquery를 사용하여 여러 부분합과 총계를 프로그래밍하고 계산하는 방법은 무엇입니까?

<table> 
<tr> 
    <td class="qty"> 
     <select class="item-1"> 
     <option value="1">1</option> 
     <option value="2">2</option> 
     <option value="3">3</option> 
     ... 
     </select> 
    </td> 
    <td class="product"> 
     Book 1 
    </td> 
    <td class="price-item-1"> 
     $20 
    </td> 
    <td class="total-item-1"> 
     $20 
    </td> 
</tr> 
<tr> 
    <td class="qty"> 
     <select class="item-2"> 
     <option value="1">1</option> 
     <option value="2">2</option> 
     <option value="3">3</option> 
     ... 
     </select> 
    </td> 
    <td class="product"> 
     Book 2 
    </td> 
    <td class="price-item-2"> 
     $10 
    </td> 
    <td class="total-item-2"> 
     $10 
    </td> 
</tr> 
... 
... 
<tr> 
    <td colspan="3" align="right"> 
     <strong>Grand Total:</strong> 
    </td> 
    <td class="grandtotal"> 
    </td> 
</tr> 
</table> 

<input type="hidden" id="qty-item-1" value="0" /> 
<input type="hidden" id="total-item-1" value="0" /> 

<input type="hidden" id="qty-item-2" value="0" /> 
<input type="hidden" id="total-item-2" value="0" /> 
+0

어떻게 jQuery를에 무엇을? 숫자를 추가하는 방법? – Tgr

답변

8

이것은 당신이 시작 얻어야한다 : 즉

$("select").change(function() { 
    var qty = $(this).val(); 

    // get the price cell by moving up a level and searching for 
    // the descendant with a class name beginning with `price'. 
    // Remove the dollar sign to do math 
    var price = $(this).closest("tr") 
         .find("td[class^=price]") 
         .html().split("$")[1]; 

    // a quantity is a whole number but a price is a float 
    var total = parseInt(qty) * parseFloat(price); 

    // write the total for this book to the 'total' cell 
    $(this).closest("tr") 
      .find("td[class^=total]") 
      .html("$" + total); 

    // sum up all the totals 
    var grandTotal = 0; 
    $("td[class^=total]").each(function() { 
     grandTotal += parseFloat($(this).html().split("$")[1]); 
    }); 

    // update the grandtotal cell to the new total 
    $(".grandtotal").html("$" + grandTotal); 
});​ 

을, 다음을 수행해야합니다

1 - 선택된 옵션의 값에서 양을 가져옵니다.

2 - 클래스가 'price'로 시작하는 동일한 행의 셀에서 가격을 가져 와서 수량에 곱한 다음 동일한 행의 '전체'셀을 업데이트하십시오.

3 - (재) 총계 (총계 합계)를 계산하고 그 값을 .grandtotal 셀에 넣습니다.

여기를보십시오 : http://jsfiddle.net/kYssr/4/

+0

+1 엄청난 설명과 실행! – Chris22

관련 문제