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

Seb*_*ham 4 html javascript jquery keyup

我正在尝试基于表单输入制作一个实时计算器,当我使用一个示例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>
Run Code Online (Sandbox Code Playgroud)

工作脚本

$('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
});
Run Code Online (Sandbox Code Playgroud)

非工作标记

<input id='total_expenses' type="text" class="form-control formBlock" name="funding"  placeholder="Total Expenses..."/>
Run Code Online (Sandbox Code Playgroud)

非工作脚本

$('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
});
Run Code Online (Sandbox Code Playgroud)

ITW*_*tch 8

这是一个有效的JSFiddle.

你一直在混淆Javascript和jQuery代码.

// Wrong code:
document.getElementById('#total_expenses').value(sum)
//Correct code:
document.getElementById('total_expenses').value() = sum
Run Code Online (Sandbox Code Playgroud)

此外,更改parseFloat为,Number以便NaN在至少有一个输入字段为空时无法获得.

奖励:更改您的<input type="text" /><input type="number" />防止"非数字"输入.

  • 我很高兴我可以帮忙:) (2认同)
  • 整洁干净的解决方案@ITWitch (2认同)