1

我创建了两个输入字段,它们应该相互减去,保持最大值为 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>

4

2 回答 2

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打折。

于 2018-08-24T10:50:15.290 回答
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>

于 2018-08-24T11:00:54.767 回答