Modificar (jQuery) JS para incluir código para realizar un seguimiento de los cambios realizados en la casilla de verificación y lista desplegable y actualización de precios

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

Pregunta

Tengo un código en javascript y estoy usando jQuery plugin de cálculo (se puede descargar desde enlace de texto ). La forma que tengo es una especie de carrito de la compra es decir, el formulario de actualización de precios de acuerdo a la cantidad introducida. El formulario tiene cuadros de texto que acepta números y esto denota la cantidad. Una vez que se introduce / modificado esta cantidad, el precio de la misma se actualiza y, al mismo tiempo, el total también se actualiza. Actualmente, sólo se me permite trabajar con cuadros de texto. Quiero ser capaz de utilizar casillas de verificación y listas desplegables en la forma y quiero el código JS para manejar la actualización del precio y el importe total y para mostrar al instante (al igual que lo haría en el caso de los cuadros de texto actuales existentes). He intentado esto en mi localhost, pero he acabado de romper la funcionalidad actual o el código actualizado simplemente no funciona para las casillas de verificación y listas desplegables.

La forma que tengo hasta ahora es:

 <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>

Además, como se puede ver el código del formulario anterior, las tablas se utilizan en ella. ¿Hay alguna forma de conseguir lo que yo estoy tratando de hacer, sin usar tablas?

Gracias a todos de antemano.

¿Fue útil?

Solución

No es una respuesta real. Sólo unas pocas notas que no encajan en un comentario.

tengo la sensación de que usted acaba de hacer un poco de pasta de copia y no tienen una comprensión real de cómo funciona este plugin cálculo. Y ahora quiere a alguien más para averiguarlo.

A pocos ejemplos:

  • que ha incluido varias funciones (mínimo, máximo, promedio), que no se utiliza y los elementos a mostrar esos valores también están desaparecidos.

  • Su código de cálculo está configurado para comprobar si hay inputs donde el nameattribute comienza con qty_item_ pero su checkbox y select tener un atributo de nombre completamente diferente.

  • el nuevo cálculo se une principalmente al evento keyup que claramente no se disparará en checkbox y select a menos que el usuario utiliza el teclado en lugar del ratón para seleccionar los valores

  • no parece estar utilizando la jQuery Plugin campo aunque el Unidos página cálculo del plugin que se necesita si desea utilizar entradas diferentes de text


Pero porque me atrapado en un buen estado de ánimo hice una simple página de demostración de trabajo para usted basado en su código.

http://jsbin.com/asepe3

Pero no voy a explicarlo más lejos, también comprobaciones de validez (sólo permiten un número entero positivo) que faltan y otras cosas.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top