2016-06-09 17 views
0

我一直在使用keyup function獲取兩個輸入值之間的確切值時很難。首先,我得到確切的結果來計算並在另一個輸入標籤中顯示結果,但是當我添加另一個時,它會顯示錯誤的結果。要理解我的意思,只需檢查下面的代碼。在關鍵函數中自動計算結果

HTML:

<input id="ivpd" type="text" name="input_vat_per_document" placeholder="Input VAT per Document"> 
<input id="gta" type="text" readonly> 
<input id="gp" type="text" readonly> 

JS:

$('#ivpd').keyup(function(){ 
    var percentage = 12/100; 
    var gta = $('#ivpd').val()/percentage; 
    var gp = $('#ivpd').val() + $('#gta').val(); 
    if (gta == Number.POSITIVE_INFINITY || gta == Number.NEGATIVE_INFINITY || isNaN(gta)) 
     gta = "N/A"; // OR 0 
    $('#gta').val(gta); 
    $('#gp').val(gp); 
}); 

例如: 如果在ivpd I輸入964.25gta8035.75gp顯示器964.298035.75這是一個錯誤的結果。它應該是ivpd + gta。的input-elements

回答

2

value屬性總是返回DOMString,如果任何操作數爲string型,Addition(+)運營商將做string concatenation操作不addition

鑄造input-valueNumber然後操縱。

Unary plus (+)unary plus operator先於其操作數,並計算其操作數,而是試圖將其轉換成number,如果它是不是已經。

注:Number可以用作以及代替Unary plus (+)

$('#ivpd').keyup(function() { 
 
    var percentage = 12/100; 
 
    var gta = +this.value/percentage; 
 
    var gp = +this.value + +$('#gta').val(); 
 
    if (gta == Number.POSITIVE_INFINITY || gta == Number.NEGATIVE_INFINITY || isNaN(gta)) 
 
    gta = "N/A"; // OR 0 
 
    $('#gta').val(gta); 
 
    $('#gp').val(gp); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<input id="ivpd" type="text" name="input_vat_per_document" placeholder="Input VAT per Document"> 
 
<input id="gta" type="text" readonly> 
 
<input id="gp" type="text" readonly>

+0

感謝快速反應:)它的工作! – claudios

+0

我注意到,在我以前的代碼中,它只能像字符串一樣輸入輸入值。 – claudios

+1

@claudios,_Yes!_檢查更新.. – Rayon

1

簡單的方法是乘IVPD和GTA值與1

  var gta = $('#ivpd').val()/percentage; 
     var ivpd= $('#ivpd').val(); 
     var gta =gta*1; 
     var gp =(ivpd *1)+ (gta*1); 

爲參比http://codepen.io/nagasai/pen/EyPVVE

+0

謝謝,但它給了'gp'中的'8999.29'。預期值應爲'9000.04' – claudios

+0

var gta = $('#ivpd')。val()/ percentage; var ivpd = $('#ivpd')。val(); var gta = gta * 1; var gp =(ivpd * 1)+(gta * 1); console.log(gta + gp); –

+0

是啊..檢查更新的codepen網址 –

1

codepen網址試試這個:

var gp = parseFloat($('#ivpd').val()) + parseFloat($('#gta').val()); 
+0

感謝它的工作也 – claudios