需求:
有一个页面需要将input框填入的各个费用自动相加,添加到“合计费用”里。
解决方案:
使用jquery的blur实践,每个费用的Input框检测到失去焦点时,将所有的input框数值相加求和,然后写入到“合计费用”框中
代码:
HTML代码如下所示
<!--管理费--><div class="form-group"><label class="col-xs-2 control-label">管理费</label><div class="input-group col-xs-8"><input type="number" class="form-control bill-count" name="fee_gl" autocomplete="off"></div></div><!--光纤费--><div class="form-group"><label class="col-xs-2 control-label">光纤费</label><div class="input-group col-xs-8"><input type="number" step="0.01" class="form-control bill-count" name="fee_gx" autocomplete="off"></div></div><!--税金--><div class="form-group"><label class="col-xs-2 control-label">税金</label><div class="input-group col-xs-8"><input type="number" step="0.01" class="form-control bill-count" name="fee_sj" autocomplete="off"></div></div><!--社保--><div class="form-group"><label class="col-xs-2 control-label">社保</label><div class="input-group col-xs-8"><input type="number" step="0.01" class="form-control bill-count" name="fee_sb" autocomplete="off"></div></div><!--公积金--><div class="form-group"><label class="col-xs-2 control-label">公积金</label><div class="input-group col-xs-8"><input type="number" step="0.01" class="form-control bill-count" name="fee_gjj" autocomplete="off"></div></div><!--残障金--><div class="form-group"><label class="col-xs-2 control-label">残障金</label><div class="input-group col-xs-8"><input type="number" step="0.01" class="form-control bill-count" name="fee_czj" autocomplete="off"></div></div><!--费用合计--><div class="form-group"><label class="col-xs-2 control-label">费用合计</label><div class="input-group col-xs-8"><input type="number" disabled id="fee-total" class="form-control" name="fee_total" value="0" autocomplete="off"></div></div>
JS代码如下所示
// 收款项失去焦点事件$('.bill-count').blur(function(){var _total = 0;$('.bill-count').each(function(){_total += Number(this.value);})$('#fee-total').val(_total);console.log(_total);})
运行结果:
如图所示,每个input框失去焦点后,会自动将所有input框的值相加填入到“费用合计”框中,达成预期效果。