Modifica (jQuery) JS per includere il codice per tenere traccia delle modifiche effettuate sulla casella di controllo e menu a discesa e prezzi aggiornamento

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

Domanda

Ho un codice in javascript e sto usando jQuery plugin di calcolo (può essere scaricato da link testuale ). La forma che ho è un po 'come carrello della spesa sotto forma cioè l'aggiornamento dei prezzi in base alla quantità inserita. Il modulo ha caselle di testo che accetta numeri e questo indica la quantità. Una volta che questa quantità viene inserito / modificato, il prezzo per la stessa viene aggiornato e allo stesso tempo, il totale viene aggiornato. Attualmente, lo lascia solo a me lavorare con caselle di testo. Voglio essere in grado di utilizzare caselle di controllo e elenchi a discesa nella forma e voglio il codice JS per gestire l'aggiornamento del prezzo e il totale complessivo e vederlo istantaneamente (proprio come farebbe nel caso degli attuali caselle di testo esistenti). Ho provato questo sul mio localhost, ma ho finito rompere la funzionalità corrente o il codice aggiornato semplicemente non funziona per le liste caselle di controllo e discesa.

La forma che ho finora è:

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

Inoltre, come si può vedere il codice modulo di cui sopra, le tabelle sono utilizzati in esso. Esiste un modo per ottenere ciò che sto cercando di fare senza usare le tabelle?

Grazie a tutti in anticipo.

È stato utile?

Soluzione

Non è una risposta reale. A pochi note che non rientrano in un commento.

ho la sensazione che hai appena fatto un po 'di copia incolla e non hanno alcuna reale comprensione di come funziona questo plugin calcolo. E ora vuole qualcun altro per capirlo.

Solo alcuni esempi:

  • hai incluso diverse funzioni (min, max, avg), che non si usa e gli elementi di visualizzare tali valori sono mancanti.

  • Il codice di calcolo è configurata per controllare inputs dove il nameattribute inizia con qty_item_ ma il vostro checkbox e select presenta un attributo nome completamente diverso.

  • il ricalcolo è legato principalmente alla manifestazione keyup che chiaramente non sparare sui checkbox e select meno che l'utente utilizza la tastiera anziché il mouse per selezionare i valori

  • che non sembrano essere utilizzando il jQuery Plugin campo anche se il Uniti Homepage calcolo di plugin che è necessario se si desidera utilizzare gli ingressi diversi da text


Ma perché mi hai catturato in un buon stato d'animo ho fatto una semplice pagina di lavoro demo per voi in base al codice.

http://jsbin.com/asepe3

Ma non voglio spiegare ulteriormente, anche controlli di integrità (consentono solo numeri interi positivi) sono mancanti e altre cose.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top