我有一个简单的计算器:
$('input').keyup(function(){ // run anytime the value changes
var firstValue = parseFloat($('#first').val()); // get value of field
var secondValue = parseFloat($('#second').val()); // convert it to a float
var thirdValue = parseFloat($('#third').val());
$('#added').html(firstValue + secondValue + thirdValue); // add them and output it
});
我需要的是总结在跨度中计算的值:budgetI + actualI
我如何获取这两个值,并将它们放在一个总和中?
答案 0 :(得分:1)
如果输入为空,则parseFloat()可以返回可能存在问题的NaN
。如果0
使用
parseFloat
,您可以指定值NaN
$('input').keyup(function () { // run anytime the value changes
var firstValue = parseFloat($('#first').val()) || 0; // get value of field
var secondValue = parseFloat($('#second').val()) || 0; // convert it to a float
var thirdValue = parseFloat($('#third').val()) || 0;
$('#added').html(firstValue + secondValue + thirdValue); // add them and output it
});
演示:Fiddle
答案 1 :(得分:1)
<强> JQuery的强>
$('input').keyup(function(){ // run anytime the value changes
var firstValue = parseFloat($('#first').val()) || 0; // get value of field
var secondValue = parseFloat($('#second').val()) || 0; // convert it to a float
var thirdValue = parseFloat($('#third').val()) || 0;
$('#added').html(firstValue + secondValue + thirdValue); // add them and output it
});
<强> HTML 强>
<input id="first"></input><br />
<input id="second"></input><br />
<input id="third"></input><br />
Total:<span id="added"></span><br />
答案 2 :(得分:0)
试试这个:
$('input').keyup(function(){ // run anytime the value changes
var firstValue = parseFloat($('#first').val()); // get value of field
var secondValue = parseFloat($('#second').val()); // convert it to a float
var thirdValue = parseFloat($('#third').val());
if(!isNaN(firstValue) && !isNaN(secondValue) && !isNaN(thirdValue))
{
$('#added').html(firstValue + secondValue + thirdValue); // add them and output it
}
});
答案 3 :(得分:0)
好的,我认为这就是你想要的。
这是html。
<input id=first></input><br />
<input id=second></input><br />
<input id=third></input><br />
Total:<span id=added></span><br />
这里是javascript
$('input').keyup(function(){ // run anytime the value changes
var firstValue = parseFloat($('#first').val()) || 0; // get value of field
var secondValue = parseFloat($('#second').val()) || 0; // convert it to a float
var thirdValue = parseFloat($('#third').val()) || 0;
$('#added').html(firstValue + secondValue + thirdValue); // add them and output it
});