2017-08-09 115 views
0

我有我的視圖中具有計算列的表中的記錄列表。表中只計算第一行的計算字段 - 循環遍歷表中的行以計算列值

List of records

從圖像,所討論的列是加價柱,並且產生/從價格,Casecost和Casesize計算出其值。此列僅對用戶可見,並且不會保存在數據庫/表中。加載頁面時計算值(超過10行的下一個/上一個)。對於記錄中的每個頁面,它僅計算圖片中第一行的值。

CSHTML我

@Html.TextBox("q_markup", null, new { @class = "calc markupclass", @readonly = "readonly" }) 

的Javascript

function calculate() { 

      //Fields that are used for calculations (declare variables) 
      var casecost = parseFloat($('#item_q_casecost').val()); 
      var casesize = parseFloat($('#item_q_casesize').val()); 
      var price = parseFloat($('#item_q_sellprice').val()); 

      //calculations 
      var unitcost = casecost/casesize; 
      var markup = ((price - unitcost)/unitcost) * 100; 

      //put calculated value into field 
      $('#q_markup').val(markup.toFixed(2));   
    } 

    $(document).ready(function() { 
     calculate(); 
    }); 

我曾經試圖要在以下方式我的計算功能的循環沒有任何成功

function calculate() { 

//gather all markup fields on page 
var rows = document.getElementsByClassName("markupclass"); 

//cycle through each rows and calculate 
for (i = 0; i < rows.length; i++) { 

    //do my calculations here 
    } 
} 

我怎麼能得到這個計算所有行的字段?

回答

0

這是我設法解決這個問題的人誰碰到這個問題

先用表我來(注:類「searchTable」

<table id="ListTable" class="table searchTable"> 
    <tr> 

通過行循環並獲得所需的值的每個字段

function calculate() { 
     $('.searchTable tr').each(function() { 

      //Fields that are used for calculations (declared variables) 
      var casecost = $(this).find('#item_q_casecost').val(); 
      var casesize = $(this).find('#item_q_casesize').val(); 
      var price = $(this).find('#item_q_sellprice').val(); 
      var vat = $(this).find('#item_viewVat').val(); 

      //calculations - PREREQUISITES 
      var unitcost = casecost/casesize; 
      var profit = (price - unitcost) - ((vat/100) * price); 

      //calculations - FIELD VALUES 
      var markup = ((price - unitcost)/unitcost) * 100; 
      var gprofit = (profit/price) * 100; 

      //assign calculated values to table fields (columns) 
      $(this).find('#q_markup').val(markup.toFixed(2)); 
      $(this).find('#q_grossprofit').val(gprofit.toFixed(2)); 

     });   
    } 

GP和標記是計算字段列(圖像)

Final result

0

不能完全確定,但你可以嘗試修理你的for循環

function calculate() { 

//gather all markup fields on page 
var rows = document.getElementsByClassName("markupclass"); 

//ADDED - middle conditional - cycle through each rows and calculate 
for (i = 0; i < rows.length; i++) { 

    //do my calculations here 
    } 
} 
+0

啊是我的一個錯字,當我插入的代碼進入正題。對於那個很抱歉。它只用該(正確)循環計算第一行。 – LavsTo

+0

是rows.length給你你正在尋找的數字?在你的計算函數中 - 這行這裏'$('#q_markup').val(markup.toFixed(2))' - 它是動態的嗎?你是否將該值應用於獨特的行? –

+0

rows.length給了我一個10的值,這個值與頁面上的10行/記錄一次是正確的。 '$('#q_markup').val(markup.toFixed(2))'行是動態的。我以爲循環會把這個值賦給唯一的行,除非我錯過了一些東西。 – LavsTo