2017-06-01 179 views
0

我正在尋找在我的表中做一些計算。表格內容來自ajax。但是對於下面的內容,計算僅完成一行(第一行)。當我試圖添加。每個函數都沒有發生。乘以兩列,結果在另一列

Ajax代碼

$.ajax({ 
     type: "Post", 
     url: '@Url.Action("function", "Controller")', 
     data: '{selectedValues: "' + selectedValues + '"}', 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function (data, textStatus, jqXHR) { 
      var row = ""; 
      $.each(data, function (index, item) { 
       row += "<tr class='odd'><td><input type='checkbox'></td><td class='product-title'>" + item.Name + "</td><td>" + item.MaxIssueLimit + "</td><td class='num-pallets'><input type='text' class='num-pallets-input' id='sparkle-num-pallets' max=" + item.MaxIssueLimit + " oninput='calculate()'></input></td><td class='times'>X</td><td class='price-per-pallet'><input type='text' class='num-pallets-input' id='cost' oninput='calculate()' value=" + item.UnitPrice + " disabled='disabled'></td><td class='equals'>=</td><td class='row-total'><input type='text' class='row-total-input' id='sparkle-row-total' disabled='disabled'></input></td></tr>";     
      }); 
      $("#contacts").html(row); 

     }, 
    }); 

的Javascript

function calculate() {    
     var my1 = document.getElementById('sparkle-num-pallets').value; 
     var my2 = document.getElementById('cost').value; 
     var result = document.getElementById('sparkle-row-total'); 
     var myResult = my1 * my2; 
     result.value = myResult;  
} 

任何幫助表示讚賞。在此先感謝

+0

[請不要把問題標題標籤(https://stackoverflow.com/help/tagging) – Liam

回答

0

你必須乘以

的parseInt函數之前,使用parseInt()函數解析一個字符串,並返回一個整數。

document.getElementById('sparkle-num-pallets').value;返回一個字符串。

你不能乘兩個字符串你有解析它們到整數。

function calculate() {    
     var my1 = document.getElementById('sparkle-num-pallets').value; 
     var my2 = document.getElementById('cost').value; 
     var result = document.getElementById('sparkle-row-total'); 
     var myResult = parseInt(my1) * parseInt(my2); // Parse the strings 
     result.value = myResult;  
} 

function calculate() { 
 
    var my1 = document.getElementById('sparkle-num-pallets').value; 
 
    var my2 = document.getElementById('cost').value; 
 
    var result = document.getElementById('sparkle-row-total'); 
 
    var myResult = parseInt(my1) * parseInt(my2); // Parse the strings 
 
    result.value = myResult; 
 
}
<table> 
 
    <tbody> 
 
    <tr> 
 
     <td><input id="sparkle-num-pallets" ></td> 
 
     <td><input id="cost" ></td> 
 
    </tr> 
 
    </tbody> 
 
</table> 
 
<button onclick="calculate()">Calculate</button> 
 
<br/> 
 
RESULT: 
 
<input id="sparkle-row-total">

+0

但我怎麼能使其所有工作表中的行@Nadir Laskar – Muzz

+0

與顯示的相同。你需要在進行任何計算之前將字符串解析爲int或float,具體取決於你想要的內容。 –