首页 > 解决方案 > 如何在javascript中创建减法函数

问题描述

  1. 我正在尝试做加法-添加所有价格和减法-减去价格函数
  2. 结果为十进制/浮点数

$('.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>

  1. 可以做减法
  2. 我希望输出为十进制/浮点数

标签: javascripthtmladdsubtraction

解决方案


如果我让您的问题正确,这应该对您有所帮助。

  1. 还要监听sub-inputs 的事件。
  2. sub减去 -inputs的值。
  3. 调用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>


推荐阅读