2010-10-16 5 views
0

Привет,Форма заказа с JQuery плагин Расчет с использованием переменной ценообразования

Я пытаюсь написать код решение для формы заказа ценовой калькулятор, используя отличную calculation plugin. Моя форма имеет две разные цены для каждого предмета: одну для величин менее 10 и одну для количества над этой суммой.

Это код, который я до сих пор:

$(document).ready(function() { 

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

    function recalc() { 

     var quantity = $("input[name^=qty_item_]").val(); 
     var quantity_int = parseInt(quantity_str); 
     var threshold = 10; 
     if (quantity_int < threshold) { 
      var useprice = $("[id^=price_item_1_]"); 
     } else { 
      var useprice = $("[id^=price_item_2_]"); 
     } 

     $("[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: useprice 
      }, 
      // 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(); 
       $("#grand_total").text(
        // round the results to 2 digits 
        "$" + sum.toFixed(2) 
       ); 
      } 

     ); 

    } 

}); 

Это близко, но useprice остается на значении, он устанавливается на первый элемент в массиве поля. Я думаю, мне нужно каким-то образом привести расчёт useprice «внутри цикла», но я зациклился на том, как это сделать.

ОБНОВЛЕНИЕ: Demo page here.

Как обычно, любая & вся помощь с благодарностью получила. TIA :)

ответ

1

Я внесла несколько изменений в ваш код. Кажется, сейчас работает. Основное изменение заключалось в пересчете только строки, которая была изменена, вместо пересчета каждой строки каждый раз. Разумеется, общая сумма по-прежнему рассчитывается по всем суммам. Я также использовал делегирование делегирования для минимизации обработчиков связанных событий, что повлияет на производительность и использование ресурсов для больших таблиц.

jQuery(
    function($) 
    { 
     // threshold that defines at what quantity to use the discounted price 
     var discountThreshold = 10; 

     // bind the recalc function to the quantity fields 
     // use event delegation to improve performance 
     $("#frmOrder") 
      .delegate(
       "input[name^=qty_item_]", 
       "keyup", 
       recalc 
      ); 

     // run the calculation function once on every quantity input 
     $("input[name^=qty_item_]").trigger("keyup"); 

     // recalculate only the changed row (and the grand total) 
     function recalc(e) { 
      // input field that triggered recalc() 
      var 
       $this = $(this), 
       $parentRow = $this.closest('tr'), 
       quantity = $this.parseNumber()[0], 
       $usePrice = ((discountThreshold <= quantity) ? $("[id^=price_item_2_]", $parentRow) : $("[id^=price_item_1_]", $parentRow)) || 0; 

      // recalculate the row price 
      $("[id^=total_item_]", $parentRow).calc(
       // the equation to use for the calculation 
       "qty * price", 
       // define the variables used in the equation, these can be a jQuery object 
       { 
        qty: $this, 
        price: $usePrice 
       }, 
       // 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 ($that){ 
        // sum the total of the $("[id^=total_item]") selector 
        var sum = $("[id^=total_item_]").sum(); 
        $("#grand_total").text(
         // round the results to 2 digits 
         "$" + sum.toFixed(2) 
        ); 
       } 
      ); 
     } 
    } 
); 
+0

Привет, Thomas, спасибо за вход, но это не так, к сожалению. Я обновил код, чтобы заставить количество в виде целого числа и собрать демонстрационную страницу. – da5id

+0

@ da5id: Я отредактировал свой ответ, чтобы предоставить вам фрагмент рабочего кода. Он должен работать так, как вам нужно сейчас. – Thomas

+0

Приветствия Томаса, который работает как шарм. Сегодня утром я проснулся, думая, что мне придется подходить к нему с совершенно другого ракурса, поэтому я не могу сказать, сколько времени вы спасли меня. Внимательно оцените, к какой длине вы шли. Еще раз спасибо :) – da5id

Смежные вопросы