체크 박스 및 드롭 다운 목록에서 변경 사항을 추적하고 가격 업데이트 가격을 추적하기위한 코드를 포함하려면 (jQuery) js를 수정합니다.

StackOverflow https://stackoverflow.com/questions/1881824

문제

JavaScript에 코드가 있고 JQuery Calculation 플러그인을 사용하고 있습니다 (다운로드 할 수 있습니다. 링크 텍스트). 내가 가진 형태는 쇼핑 카트 형태와 비슷합니다. 즉, 입력 한 수량에 따라 가격 업데이트입니다. 양식에는 숫자를 받아들이는 텍스트 상자가 있으며 이것은 수량을 나타냅니다. 이 수량을 입력/수정하면 동일한 가격이 업데이트되고 동시에 Grand Total도 업데이트됩니다. 현재 텍스트 상자로 만 작업 할 수 있습니다. 양식으로 확인란 및 드롭 다운 목록을 사용하고 JS 코드가 가격 업데이트 및 그랜드 총계를 처리하고 즉시 표시 할 수 있고 (현재 기존 텍스트 상자의 경우와 마찬가지로) 즉시 표시하고 싶습니다. LocalHost에서 이것을 시도했지만 현재 기능을 해체하거나 업데이트 된 코드가 확인란 및 드롭 다운 목록에 대해서는 작동하지 않습니다.

지금까지 가지고있는 형태는 다음과 같습니다.

 <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/jquery.calculation.js" type="text/javascript"></script>


<SCRIPT type="text/javascript">
var bIsFirebugReady = (!!window.console && !!window.console.log);

$(document).ready(
    function (){
        // update the plug-in version
        $("#idPluginVersion").text($.Calculation.version);


        // bind the recalc function to the quantity fields
        $("input[name^=qty_item_]").bind("keyup", recalc);
        // run the calculation function now
        recalc();

        // automatically update the "#totalSum" field every time
        // the values are changes via the keyup event
        $("input[name^=sum]").sum("keyup", "#totalSum");

        // automatically update the "#totalAvg" field every time
        // the values are changes via the keyup event
        $("input[name^=avg]").avg({
            bind:"keyup"
            , selector: "#totalAvg"
            // if an invalid character is found, change the background color
            , onParseError: function(){
                this.css("backgroundColor", "#cc0000")
            }
            // if the error has been cleared, reset the bgcolor
            , onParseClear: function (){
                this.css("backgroundColor", "");
            }
        });

        // automatically update the "#minNumber" field every time
        // the values are changes via the keyup event
        $("input[name^=min]").min("keyup", "#numberMin");

        // automatically update the "#minNumber" field every time
        // the values are changes via the keyup event
        $("input[name^=max]").max("keyup", {
            selector: "#numberMax"
            , oncalc: function (value, options){
                // you can use this to format the value
                $(options.selector).val(value);
            }
        });

        // this calculates the sum for some text nodes
        $("#idTotalTextSum").click(
            function (){
                // get the sum of the elements
                var sum = $(".textSum").sum();

                // update the total
                $("#totalTextSum").text("$" + sum.toString());
            }
        );

        // this calculates the average for some text nodes
        $("#idTotalTextAvg").click(
            function (){
                // get the average of the elements
                var avg = $(".textAvg").avg();

                // update the total
                $("#totalTextAvg").text(avg.toString());
            }
        );
    }
);

function recalc(){
    $("[id^=total_item]").calc(
        // the equation to use for the calculation
        "qty * price",
        // define the variables used in the equation, these can be a jQuery object
        {
            qty: $("input[name^=qty_item_]"), 
            price: $("[id^=price_item_]"),

        },
        // define the formatting callback, the results of the calculation are passed to this function
        function (s){
            // return the number as a dollar amount
            return "$" + s.toFixed(2);
        },
        // define the finish callback, this runs after the calculation has been complete
        function ($this){
            // sum the total of the $("[id^=total_item]") selector
            var sum = $this.sum();

            $("#grandTotal").text(
                // round the results to 2 digits
                "$" + sum.toFixed(2)
            );
        }
    );
}
</SCRIPT> 



<form name="form1" method="post" action="">

<div id="formContent">

  <P id="ex-sum">
  <table width="500">
                <COL style="width: 50px;">
                <COL>
                <COL style="width: 60px;">
                <COL style="width: 110px;">
                <tbody><tr>
                    <th width="179">
                        Qty
                    </th>
                    <th width="164" align="left">
                        Product
                    </th>
                    <th width="72">
                        Price
                    </th>
                    <th width="65">
                        Total
                    </th>
                </tr>
                <tr>
                    <td align="center">
                        <INPUT name="qty_item_1" type="text" class="input" id="qty_item_1" value="1" size="5">
                  </td>
                    <td>Table</td>
                    <td align="center" id="price_item_1">
                        $150
                    </td>
                    <td align="center" id="total_item_1">$</td>
                </tr>
                <tr>
                    <td align="center">
                        <INPUT name="qty_item_2" type="text" class="input" id="qty_item_2" size="5">
                  </td>
                    <td>
                        Pencil</td>
                    <td align="center" id="price_item_2">
                        $100</td>
                    <td align="center" id="total_item_2">$</td>
                </tr>
                <tr>
                    <td align="center">
                        <INPUT name="toys" type="checkbox" id="toys" value="1">
              </td>
                  <td>
                        Toys</td>
                    <td align="center" id="price_item_3">
                        $50</td>
                    <td align="center" id="total_item_3">$</td>
                </tr>  

              <tr>
                    <td align="center"><select name="books" id="books">
                      <option selected="selected">Select an option</option>
                      <option value="1">Book1</option>
                      <option value="1">Book2</option>
                      <option value="1">Book3</option>
                    </select></td>
                  <td>
                        Books</td>
                    <td align="center" id="price_item_3">
                        $10</td>
                    <td align="center" id="total_item_3">$</td>
                </tr>

                <tr>
                    <td colspan="3" align="right">
                        <STRONG>Grand Total:</STRONG>
                    </td>
                    <td align="center" id="grandTotal">$</td>
                </tr>
            </tbody></table>
</div>

</form>

또한 위의 양식 코드를 볼 수 있듯이 테이블이 사용됩니다. 어쨌든 테이블을 사용하지 않고 내가하려는 일을 달성 할 수 있습니까?

미리 감사드립니다.

도움이 되었습니까?

해결책

진정한 대답이 아닙니다. 의견에 맞지 않는 몇 개의 메모 만 있습니다.

나는 당신이 단지 복사 페이스트를 했고이 계산 플러그인이 어떻게 작동하는지 이해하지 못한다는 느낌이 들었습니다. 그리고 이제 다른 사람이 그것을 알아 내기를 원합니다.

몇 가지 예 만 :

  • 사용하지 않는 여러 기능 (Min, Max, AVG)이 포함되어 있으며 해당 값을 표시하는 요소도 누락되었습니다.

  • 계산 코드는 확인하도록 구성됩니다 inputs name속성은 시작합니다 qty_item_ 하지만 당신의 checkbox 그리고 select 완전히 다른 이름 속성이 있습니다.

  • 재 계산은 주로에 묶여 있습니다 keyup 분명히 해고하지 않는 이벤트 checkbox 그리고 select 사용자가 마우스 대신 키보드를 사용하여 값을 선택하지 않는 한

  • 당신은 사용하지 않는 것 같습니다 jQuery 필드 플러그인 계산 플러그인 홈페이지는 다른 입력을 사용하려면 필요하다고 말하지만 text


그러나 당신은 기분이 좋았 기 때문에 코드를 기반으로 간단한 작업 데모 페이지를 만들었습니다.

http://jsbin.com/asepe3

그러나 더 이상 설명하지 않을 것입니다. 또한 세력 검사 (양수 정수 번호 만 허용)가 누락되고 다른 것들이 누락되었습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top