javascript - 如何在javascript中创建减法函数
问题描述
- 我正在尝试做加法-添加所有价格和减法-减去价格函数
- 结果为十进制/浮点数
$('.add').keyup(function () {
var sum = 0;
$('.add').each(function() {
sum += Number($(this).val());
});
$('#total').val(sum);
});
<strong>price1 : </strong>
<input type="text" name="IT" class="add" style="width:150px" required><br><br>
<strong>price2 : </strong>
<input type="text" name="roadtax" class="add" style="width:150px" required><br><br>
<strong>price3 : </strong>
<input type="text" name="servis" class="add" style="width:150px" required><br><br>
<strong>price4 : </strong>
<input type="text" name="other" class="add" style="width:150px" required><br><br>
<strong>discount : </strong>
<input type="text" name="disc" class="sub" style="width:150px" required><br><br>
<strong>total : </strong>
<input type="text" id="total" name="total" style="width:150px">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
- 可以做减法
- 我希望输出为十进制/浮点数
解决方案
如果我让您的问题正确,这应该对您有所帮助。
- 还要监听
sub
-inputs 的事件。 sub
减去 -inputs的值。- 调用
toFixed
总和以获得十进制输出。
$('.add, .sub').keyup(function () { // 1
var sum = 0;
$('.add').each(function() {
sum += Number($(this).val());
});
$('.sub').each(function() {
sum -= Number($(this).val()); // 2
});
$('#total').val(sum.toFixed(2)); // 3
});
<strong>price1 : </strong><input type="text" name="IT" class="add" style="width:150px" required><br><br>
<strong>price2 : </strong><input type="text" name="roadtax" class="add" style="width:150px"required><br><br>
<strong>price3 : </strong><input type="text" name="servis" class="add" style="width:150px"required><br><br>
<strong>price4 : </strong><input type="text" name="other" class="add" style="width:150px"required><br><br>
<strong>discount : </strong><input type="text" name="disc" class="sub" style="width:150px"required><br><br>
<strong>total : </strong><input type="text" id="total" name="total" style="width:150px">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
推荐阅读
- python - 我目前正在处理 MAC 转换器脚本,我遇到了一个错误
- java - Kotlin:[内部错误] java.lang.NoClassDefFoundError:无法初始化类 com.intellij.pom.java.LanguageLevel
- pandas - 通过带有集合模式的 pandas 前向填充方法估算 NAN 值
- c# - 传输asp.net webform后一些数据库数据出现问题
- c# - 为什么我们需要对 Parse 方法返回的对象进行强制转换?
- linq - InvalidOperationException:LINQ 表达式“GroupByShaperExpression:
- macos - PCIDriverKit 授权检查失败(将 KEXT 迁移到 DEXT)
- angular - 获取数组长度为 0 而不是正确的长度
- r - 将年龄组的顺序改为正常顺序
- python - 这是我的代码中的错误“TypeError:'pygame.Surface'类型的对象没有len()”,我在这里得到它“如果for_count> = len(for_enemy_list)”