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



我正在尝试根据表单输入进行实时计算器,当我使用示例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
});

这是一个工作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" />,以防止"非数字"输入。

您可以尝试此jQuery代码

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

首先,当使用getElementById时,您可以省略#。其次,使用Vanilla JS为输入分配值是通过简单分配而不是函数调用来完成的。因此,该线应该看起来像这样:

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

相关内容

  • 没有找到相关文章

最新更新