工作加价解决方案:
<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计算所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)