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

基于表单输入的实时Javascript计算,第1张

概述我正在尝试基于表单输入制作一个实时计算器,当我使用一个示例div它可以工作,但当我尝试在输入中打印总数时,我似乎错过了一些东西…… 工作加价解决方案: <input id='first' type="text" class="form-control formBlock" name="bus_ticket" placeholder="Bus Ticket..." required/><br /> 我正在尝试基于表单输入制作一个实时计算器,当我使用一个示例div它可以工作,但当我尝试在输入中打印总数时,我似乎错过了一些东西……

工作加价解决方案:

<input ID='first' type="text"  name="bus_ticket"  placeholder="Bus Ticket..." required/><br /><input ID='second' type="text"  name="plane_ticket"  placeholder="Plane Ticket..." required/><br /><input ID='third' type="text"  name="hotel_expenses"  placeholder="Hotel Expenses..." required/><br /> <input ID='fourth' type="text"  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"  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});
解决方法

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”/>防止“非数字”输入.

总结

以上是内存溢出为你收集整理的基于表单输入的实时Javascript计算全部内容,希望文章能够帮你解决基于表单输入的实时Javascript计算所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1046179.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存