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