自动从100减去这两个值

时间:2018-08-24 10:44:56

标签: javascript jquery

我创建了两个输入字段,它们应该彼此相减,并将最大值保持为100。

当前减去的值显示在第二个值中。我希望它可以互换。不管我输入第一个还是第二个输入字段,答案都将显示在另一个字段中。

有人可以帮忙吗?

function updateDue() {
    var total = parseInt(document.getElementById("totalval").value);
    var val2 = parseInt(document.getElementById("inideposit").value);
    // to make sure that they are numbers
    if (!total) { total = 0; }
    if (!val2) { val2 = 0; }
    var ansD = document.getElementById("remainingval");
    ansD.value = total - val2;
    var val1 = parseInt(document.getElementById("inideposit").value);
    // to make sure that they are numbers
    if (!total) { total = 0; }
    if (!val1) { val1 = 0; }
    var ansD = document.getElementById("remainingval");
    ansD.value = total - val1;
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue()">
<div>
  Enter Value:
  <input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue()">
</div>
<div>
  Substracted:
  <input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue()">
</div>

2 个答案:

答案 0 :(得分:2)

实现此目的的简单方法是按类对输入进行分组,并将单个事件处理程序附加到它们。然后,您可以从100中获取输入的值,并将结果设置为用户未与之交互的字段。在jQuery中做到这一点很简单:

$('.updatedue').on('input', function() {  
  var total = parseInt($('#totalval').val(), 10) || 0;
  var subtracted = total - (parseInt(this.value, 10) || 0);
  $('.updatedue').not(this).val(subtracted);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="totalval" name="totalval" value="100" />
<div>
  Enter Value:
  <input type="text" name="inideposit" class="updatedue form-control" id="inideposit" />
</div>
<div>
  Subtracted:
  <input type="text" name="remainingval" class="updatedue form-control" id="remainingval" />
</div>

您可以轻松地对此进行验证,以便可以根据需要对输出< 0> 100进行打折。

答案 1 :(得分:1)

按如下所示编辑代码

function updateDue(box) {

    var total = parseInt(document.getElementById("totalval").value);
    if(box == 1){
        var val = parseInt(document.getElementById("inideposit").value);
        // to make sure that they are numbers
        if (!total) { total = 0; }
        if (!val) { val = 0; }
        var ansD = document.getElementById("remainingval");
        ansD.value = total - val;
    }else if(box == 2){
        var val = parseInt(document.getElementById("remainingval").value);
        // to make sure that they are numbers
        if (!total) { total = 0; }
        if (!val) { val = 0; }
        var ansD = document.getElementById("inideposit");
        ansD.value = total - val;
    }
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue(0)">
<div>
  Enter Value:
  <input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue(1)">
</div>
<div>
  Substracted:
  <input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue(2)">
</div>