2016-02-14 89 views
1

这里是用于计算物品价格的问题是 每当价格是4位时,返回的值是NaN。Javascript总回报NaN为4位数字

这里是我的价格隐藏字段:

<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> 
+0

'返回的值 - - 返回的值在哪里?注意:这是一个真正的混乱jquery和纯javascript - 为什么这样的mashup?总是使用jQuery风格的代码,或从来没有使用它,与您发布的代码没有多大意义,有这样的混合(在我看来) –

+1

所有作品对我来说 - https://jsfiddle.net/ermakovnikolay/ yop9ondz/ –

+0

如果您打算使用Jquery,请使用'.on('input')'事件方法。它比'keyup'绑定更健壮。 – magreenberg

回答

1

不知道(缺少右括号)问题区域附近:

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