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

4

我正在尝试基于表单输入制作实时计算器,当我使用示例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
});
3个回答

9

这是一个有效的JSFiddle链接。

您混淆了JavaScript和jQuery代码。

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

此外,将parseFloat更改为Number,以避免在至少一个输入字段为空时出现NaNBONUS:<input type="text" />更改为<input type="number" />以防止“非数字”输入。

1
非常整洁。谢谢。 - Sebastian Farham
2
我很高兴能够帮到你 :) - ITWitch
2
好的整洁解决方案 @ITWitch - bharat savani

1
你可以尝试这个 jQuery 代码。
var totalValue = firstValue + secondValue + thirdValue + fourthValue;
$('#total_expenses').val(totalValue);

1
首先,在使用getElementById时,您可以省略#。其次,使用vanilla JS对输入框进行赋值是通过简单的赋值而不是函数调用完成的。因此,该行应该像这样:
document.getElementById('total_expenses').value = firstValue + secondValue + thirdValue + fourthValue;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接