乘以时NaN错误

时间:2016-09-28 13:14:14

标签: javascript jquery nan

我有这个脚本来乘以两列并在第三列中显示总数。这是代码:

<script>
$(function() {
    $("#num1, #num2").on("keydown keyup", sum);
    function sum() {
    $("#total").val(Number($("#num1").val()) * Number($("#num2").val()));
    }
});
 </script>

并形成:

<form method="POST" name="form1" action="" ">

<label>num1</label> 
<input name="num1" id="num1" type="text" value="SOMENUMBER" />

<label>num2</label>
<input type="text"   name="num2" id="num2" value="SOMENUMBER"/>

<label>total</label> 
<input type="text"  name="total" style="width: 40%;" id="total" readonly />

<button class="square" name="btn" type="submit">SOMEBUTTONNAME</button>

</form>

2 个答案:

答案 0 :(得分:2)

先检查您是否有有效的号码

function sum() { 

    var value1 = $("#num1").val();
    var value2 = $("#num2").val();

    if (isNaN(value1) || isNaN(value2){
        return;
    }

    $("#total").val(Number(value1) * Number(value2));
}

答案 1 :(得分:1)

HTML中有3x "action="" "

此代码可防止出现非数字字符并计算单击按钮上的结果或更改某些数字。

function sum() {
  var num1 = $("#num1").val().replace(",",".");
  var num2 = $("#num2").val().replace(",",".");
  var decimals_prepare = (num1.indexOf(".") > -1) ? num1.split(".")[1].length : 0;
  
  return (!isNaN(num1) && !isNaN(num2)) ? $("#total").val((num1 * num2).toFixed(decimals_prepare)) : console.log("false");
}

$(function() {
  $("#num1, #num2").on("keydown keyup", sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" name="form1" action="">

  <label>num1</label>
  <input name="num1" id="num1" type="text" value="5" />

  <label>num2</label>
  <input type="text" name="num2" id="num2" value="2" />

  <label>total</label>
  <input type="text" name="total" style="width: 40%;" id="total" readonly />

  <button class="square" name="btn" type="submit" onclick="sum()">SOMEBUTTONNAME</button>

</form>