簡體   English   中英

將兩列相乘,得出另一列

[英]Multiply two columns and result in another column

我想在表中進行一些計算。 該表的內容來自ajax。 但是,使用以下內容,計算僅針對一行(第一行)完成。 當我嘗試使用功能添加.each時,沒有任何反應。

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

任何幫助表示贊賞。 提前致謝

您必須在乘法之前使用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"> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM