如何用jQuery总结span的值?

时间:2014-09-13 17:43:03

标签: jquery

我有一个简单的计算器:

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

http://jsfiddle.net/5xzSy/1

我需要的是总结在跨度中计算的值:budgetI + actualI

我如何获取这两个值,并将它们放在一个总和中?

4 个答案:

答案 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 />

DEMO

答案 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
  }
});

DEMO

答案 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
});