当输入字段为空时,Javascript 计算返回 NaN

xhi*_*vis 1 html javascript

我必须使用 javascript 使用表单字段中的值进行小计算。计算公式如下:

totalIncome = income1 + income2 *0.7 + income3/48 + (income4 * 0.7)/48;

的值income1income2income3income4可以是零和字段可以是空的。

我的代码如下:

 <tr id="row">
  <td>No. of Dependant(s)</td>
  <td><input type="text" id="income1" value=""></td>
  <td><input type="text" id="income2" value=""></td>
  <td><input type="text" id="income3" value=""></td>
  <td><input type="text" id="income4" value=""></td>
  <td><input type="text" id="totalIncome" readonly></td>
</tr>
Run Code Online (Sandbox Code Playgroud)

我用于我的公式的公式脚本如下:

var income1 = document.getElementById("income1");
var income2 = document.getElementById("income2");
var income3 = document.getElementById("income3");
var income4 = document.getElementById("income4");
var totalIncome = document.getElementById("totalIncome");

var inputs = Array.prototype.slice.call(document.querySelectorAll("td > input"));

inputs.forEach(function(input){

  input.addEventListener("blur", function(){
    // Always supply the second argument to parseInt() (the radix) so you
    // dont' get non-base 10 answers.
    totalIncome.value = parseInt(income1.value, 10) + parseInt(income2.value, 10)* 0.7  + parseInt(income3.value, 10)/48 + (parseInt(income4.value, 10)*0.7)/48;


  });

});
Run Code Online (Sandbox Code Playgroud)

但是,当某些字段为空时,我不确定为什么totalIncome会变成这样NaN

Ang*_*ris 5

您可以||0与您的parseInt()调用结合使用以确保返回的值始终为数字,并且在空<input>字段的情况下为0。

var income1 = document.getElementById("income1");
var income2 = document.getElementById("income2");
var income3 = document.getElementById("income3");
var income4 = document.getElementById("income4");
var totalIncome = document.getElementById("totalIncome");

var inputs = Array.prototype.slice.call(document.querySelectorAll("td > input"));

inputs.forEach(function(input) {

  input.addEventListener("blur", function() {
    totalIncome.value =
      (parseInt(income1.value, 10) || 0) +
      (parseInt(income2.value, 10) || 0) * 0.7 +
      (parseInt(income3.value, 10) || 0) / 48 +
      ((parseInt(income4.value, 10) || 0) * 0.7) / 48;
  });
});
Run Code Online (Sandbox Code Playgroud)
<table>
  <tr id="row">
    <td>No. of Dependant(s)</td>
    <td><input type="text" id="income1" value=""></td>
    <td><input type="text" id="income2" value=""></td>
    <td><input type="text" id="income3" value=""></td>
    <td><input type="text" id="income4" value=""></td>
    <td><input type="text" id="totalIncome" readonly></td>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

更新

在 OP 要求之后,您可以显示toFixed(2),稍微改变计算totalIncome.value如下:

totalIncome.value = (
  (parseInt(income1.value, 10) || 0) +
  (parseInt(income2.value, 10) || 0) * 0.7 +
  (parseInt(income3.value, 10) || 0) / 48 +
  ((parseInt(income4.value, 10) || 0) * 0.7) / 48).toFixed(2);
Run Code Online (Sandbox Code Playgroud)