Javascript 总返回 NaN 为 4 位数字

标签 javascript php jquery html codeigniter

这是用于计算商品价格的 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> 

更 retrofit 运值(value)的脚本

<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!');
}

关于Javascript 总返回 NaN 为 4 位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35388684/

相关文章:

javascript - 你能对 html 脚本中双花括号内的变量进行数学运算吗?

javascript - onChange 文本区域检测和清除输入字段

javascript - 当我提交表单时,仅从多输入名称给出一个值

php - fatal error : Call to a member function load() on a non-object (P4A application Framework)

javascript - 当ID在对象外部时如何将其移动到对象内部?

javascript - 尝试将 Tributary D3.js 示例转移到 JSFiddle

php - 从另一个表中选择多个列,其中字段包含数组

javascript - 在第二次尝试中计数意外地增加了 2,而我将其编码为仅增加 1?

javascript - 通过 ajax 通过一个按钮将单个表单提交给两个操作

javascript - 通过ajax将值数组提交到外部php脚本(数据表延迟渲染)