将两列相乘并生成另一列

时间:2017-06-01 10:24:49

标签: javascript jquery asp.net-mvc-4

我希望在我的桌子上做一些计算。表格内容来自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;     
}

任何帮助表示赞赏。提前致谢

1 个答案:

答案 0 :(得分:0)

在乘以

之前,您必须使用this answer
  

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

&#13;
&#13;
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;
}
&#13;
<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">
&#13;
&#13;
&#13;