Javascript 总返回 NaN 为 4 位数字


Javascript total return NaN for 4 digits num

这是用于计算项目价格的javascript,问题是每当价格为 4 位时,返回的值为 NaN。

这是我的价格隐藏字段:

<input type="hidden" name="price" id="price"class="price" value="4500"readonly >

这是我的数量字段

<input type="number" name="quant" id="quant" value="2" />

这是我的运费

<select  id="shipment" onchange="myFunction3()" name="shipment2" disabled>
<option value="100" data-quantity="1">1 for 100 pesos </option>
</select

这是总价

<input type="text" id="demo" name="total_price" style="margin-top:10px;margin-left:5px;" readonly> 

用于更改货件价值的脚本

<script type="text/javascript">
document.getElementById('quant').addEventListener("keyup", function(){
  var value = parseInt(this.value, 20),
      selectEle = document.getElementsByTagName('select')[0],
      options = selectEle.options,
      selectedNum = 0;
  for(var i = 0; i < options.length; i++) {
    //checking the exact string with spaces (" " + value + " ")
    if(options[i].textContent.indexOf(" " + value + " ") > -1) {
        selectedNum = i;
    }
 }
 selectEle.selectedIndex = selectedNum ? selectedNum : 0;   
 }, false);
 </script>

计算所有值

function myFunction3() {
var y= document.getElementById("shipment").value;
return y;
}
<script>
    $("#price,#quant,#shipment").keyup(function () {
      if(+myFunction3() =="" )
      {
        $('#demo').val(0);
      }
      else if($('#trigger')=="checked") //this is the problem
      {
        $('#demo').val($('#price').val() * $('#quant').val() ;
      }
      else
      {
      $('#demo').val($('#price').val() * $('#quant').val() + +myFunction3());
     }
  });
  </script>

不确定这是否只是在这里输入错误,但是您在问题区域附近有一个语法错误(缺少右括号(:

$('#demo').val($('#price').val() * $('#quant').val() ;

应该是:

$('#demo').val($('#price').val() * $('#quant').val());

我认为在对字符串进行数学运算之前,确保您不使用字符串会好得多:

var price = parseInt($('#price').val(), 10);
var quantity = parseInt($('#quant').val(), 10);
$('#demo').val(price * quantity);

您可以更进一步,确保在与他们合作之前,它们都不NaN

var price = parseInt($('#price').val(), 10);
var quantity = parseInt($('#quant').val(), 10);
if(!isNaN(price) && !isNaN(quantity)) {
  $('#demo').val(price * quantity);
} else {
  alert('Please enter numbers only!');
}