基于表单输入的实时 Javascript 计算

Real Time Javascript Calculation Based On Form Inputs

我正在尝试制作一个基于表单输入的实时计算器,当我使用示例时 div 它可以工作,但是当我尝试在输入中打印总数时我似乎遗漏了一些东西...

工作标记解决方案:

 <input id='first' type="text" class="form-control formBlock" name="bus_ticket"  placeholder="Bus Ticket..." required/><br />

<input id='second' type="text" class="form-control formBlock" name="plane_ticket"  placeholder="Plane Ticket..." required/><br />

<input id='third' type="text" class="form-control formBlock" name="hotel_expenses"  placeholder="Hotel Expenses..." required/><br />

 <input id='fourth' type="text" class="form-control formBlock" name="eating_expenses"  placeholder="Eating Expenses..." required/><br />

Total : <span id="total_expenses"></span>

工作脚本

$('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());
    var fourthValue = parseFloat($('#fourth').val());

    $('#total_expenses').html(firstValue + secondValue + thirdValue + fourthValue); // add them and output it
});

无效标记

<input id='total_expenses' type="text" class="form-control formBlock" name="funding"  placeholder="Total Expenses..."/>

非工作脚本

$('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());
    var fourthValue = parseFloat($('#fourth').val());
    document.getElementById('#total_expenses').value(firstValue + secondValue + thirdValue + fourthValue);
// add them and output it
});

你可以试试这个jquery代码

var totalValue = firstValue + secondValue + thirdValue + fourthValue;
$('#total_expenses').val(totalValue);

首先,使用 getElementById 时可以省略#。其次,使用 vanilla JS 为输入赋值是通过简单赋值完成的,而不是函数调用。所以那一行应该是这样的:

document.getElementById('total_expenses').value = firstValue + secondValue + thirdValue + fourthValue;

Here's a working JSFiddle.

您混淆了 Javascript 和 jQuery 代码。

// Wrong code:
document.getElementById('#total_expenses').value(sum)
//Correct code:
document.getElementById('total_expenses').value() = sum

此外,将 parseFloat 更改为 Number,这样当至少有一个输入字段为空白时,您不会得到 NaN

奖励: 将您的 <input type="text" /> 更改为 <input type="number" /> 以防止 "non-numerical" 输入。