使用复选框决定要求和的输入框值

Using checkbox to decide which input boxes value to sum

本文关键字:和的 输入 求和 复选框 决定      更新时间:2023-09-26

我正在尝试编写一些Javascript/jQuery来对在多个文本框中输入的值求和。

每个输入框都有一个与之关联的复选框,基于该复选框,该值将添加到总数中。例如,如果用户选择Activity feesTransport fees,则它们应该相加,如果他选择也将相加的Misc fees,并且如果他随后取消选中Misc fees,则应该再次减去该值。

function optionalfee() {
    var total = 0;
    var fee = document.getElementsById('optional1');
    for (var i = 0; i < fee.length; ++i) {
      if (optional1.checked == true)
        document.getElementById('optional').value = fee;
      total += parseFloat(fee.value);
    }
  } else {
    total -= parseFloat(fee.value);
  }
  //alert(total);
document.getElementById('toptional').value = total;
}
Include Activity fees <input type="checkbox" id="optional1" /><input type="number" id="optional" name="afees"><br><br>
Include Transport fees <input type="checkbox" id="optional1" /><input type="number" id="optional" name="tfees"><br><br>
Include Misc fees <input type="checkbox" id="optional1" /><input type="number" id="optional" name="mfees"><br><br>
Include Olympiad fees <input type="checkbox" id="optional1" /><input type="number" id="optional" name="ofees"><br><br>
Optional fees total <input type="number" id="toptional" name="toptional" class="toptional" readonly>

  1. 使所有ID唯一
  2. 而是使用了类
  3. 添加了缺少的括号
  4. isNaN和空的测试值
  5. 号码更改时也会更新

注意,我正在使用id 的数据属性

普通JS:

function optionalfee() {
  var total = 0;
  // get the checked boxes only
  document.querySelectorAll('.optional:checked').forEach(check => {
    // find the ID of the input to use
    var input = document.getElementById(check.getAttribute("data-id"));
    var val = input.value;
    // handle poor or no input - is in principle already handled by the type="number"
    val = (isNaN(val) || "" === val.trim()) ? 0 : parseFloat(val);
    total += val;
  })
  document.getElementById('toptional').value = total;
}
window.addEventListener("DOMContentLoaded", () => {
  const checks = document.querySelectorAll(".optional"),
    fees = document.querySelectorAll(".fee");
  checks.forEach((check, i) => {
    checks[i].onclick = optionalfee;
    fees[i].oninput = optionalfee;
  })
})
Include Activity fees
<input type="checkbox" class="optional" data-id="optional1" />
<input type="number" class="fee" id="optional1" name="afees">
<br>
<br>Include Transport fees
<input type="checkbox" class="optional" data-id="optional2" />
<input type="number" class="fee" id="optional2" name="tfees">
<br>
<br>Include Misc fees
<input type="checkbox" class="optional" data-id="optional3" />
<input type="number" class="fee" id="optional3" name="mfees">
<br>
<br>Include Olympiad fees
<input type="checkbox" class="optional" data-id="optional4" />
<input type="number" class="fee" id="optional4" name="ofees">
<br>
<br>Optional fees total
<input type="number" id="toptional" name="toptional" class="toptional" readonly>

jQuery:

function optionalfee() {
  var total = 0;
  $('.optional:checked').each(function() {
    var val = $("#"+$(this).data("id")).val();
    val = isNaN(val) || "" === $.trim(val) ? 0 : parseFloat(val);
    total += val;
  });
  $('#toptional').val(total);
}
$(function() {
  $(".optional").each(function() {
    $(this).on("click", optionalfee);
    // if not next to each other, 
    // use  $("#"+$(this).data("id")).on("input", optionalfee);
    $(this).next().on("input", optionalfee);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Include Activity fees
<input type="checkbox" class="optional" data-id="optional1" />
<input type="number" class="fee" id="optional1" name="afees">
<br>
<br>Include Transport fees
<input type="checkbox" class="optional" data-id="optional2" />
<input type="number" class="fee" id="optional2" name="tfees">
<br>
<br>Include Misc fees
<input type="checkbox" class="optional" data-id="optional3" />
<input type="number" class="fee" id="optional3" name="mfees">
<br>
<br>Include Olympiad fees
<input type="checkbox" class="optional" data-id="optional4" />
<input type="number" class="fee" id="optional4" name="ofees">
<br>
<br>Optional fees total
<input type="number" id="toptional" name="toptional" class="toptional" readonly>

<input type="checkbox" id="afees" class="sum-checkbox" />
<input type="number" id="optional" name="afees">

指定input#number name作为相应复选框的id。为必填复选框添加一个公共类(e.g. sum-checkbox)

var sumAll = 0;
$(".sum-checkbox").on('change',function(){
    var currentCheck = $(this);
   var checkId = $(currentCheck).attr('id');
    if(currentCheck.prop('checked')){
        sumAll += parseInt(inputVal);
    }else{
        sumAll -= parseInt(inputVal);
    }

})

id在同一文档中应该是唯一的,但您可以在不使用这些id的情况下实现您想要的,请使用:checked检查下面的示例以获得选中的复选框,然后使用each()检查它们并计算总数。

希望这能有所帮助。

function calculate_sum() {
  var total = 0;
  $('input[type="checkbox"]:checked').each(function(){
    total += parseInt( $(this).next('input').val() );
  })
  $('#toptional').val(total);
}
$('input[type="checkbox"]').on('change', function(){
  calculate_sum();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Include Activity fees <input type="checkbox" id="optional11" /><input type="number" id="optional1" name="afees"><br><br>
Include Transport fees <input type="checkbox" id="optional22" /><input type="number" id="optional2" name="tfees"><br><br>
Include Misc fees <input type="checkbox" id="optional33" /><input type="number" id="optional3" name="mfees"><br><br>
Include Olympiad fees <input type="checkbox" id="optional44" /><input type="number" id="optional4" name="ofees"><br><br><hr>
Optional fees total <input type="number" id="toptional" name="toptional" class="toptional" readonly>

JavaScript,每当元素checkboxinput分别收到点击或输入时,将在多个数字输入中输入的值相加:

var total = document.getElementById('toptional'),
    checkboxs = document.getElementsByClassName('checkbox'),
    inputs = document.getElementsByClassName('fee'),
    getTotalFee = function() {
        var totalFee = 0;
        for (var i = 0, len = checkboxs.length; i < len; i++) {
            checkboxs[i].checked && (totalFee += +inputs[i].value);
        }
        total.value = totalFee;
    };
for (var i = 0, len = checkboxs.length; i < len; i++) {
    checkboxs[i].addEventListener('click', getTotalFee, false);
    inputs[i].addEventListener('input', getTotalFee, false);
}
Include Activity fees: 
<input type="checkbox" class="checkbox">
<input type="number" name="afees" class="fee"><br>
Include Transport fees: 
<input type="checkbox" class="checkbox">
<input type="number" name="tfees" class="fee"><br>
Include Misc fees: 
<input type="checkbox" class="checkbox">
<input type="number" name="mfees" class="fee"><br>
Include Olympiad fees: 
<input type="checkbox" class="checkbox">
<input type="number" name="ofees" class="fee"><br>
<br><br><hr>
<strong>Optional fees total:</strong>
<input type="number" id="toptional" name="toptional" value="0" class="toptional" readonly>

首先我注意到您正在为许多元素设置id="optional1",请记住id是标识符,它在html文档中应该是唯一的。

检查代码

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<script type="text/javascript">
function optionalfee(){
    var total = 0;
    for (var i = 1; i<=4; ++i){ 
        var fee = document.getElementById('optional'+i);
        if(fee.checked==true){
            total += parseFloat(document.getElementById('optional-fee'+i).value);
        }
     }
    //alert(total);
    document.getElementById('toptional').value = total;
}
</script>
</head>
<body>
Include Activity fees <input type="checkbox" id="optional1" onclick="optionalfee()" /> <input type="number" id="optional-fee1" name="afees"><br><br>
Include Transport fees <input type="checkbox" id="optional2" onclick="optionalfee()" /> <input type="number" id="optional-fee2" name="tfees"><br><br>
Include Misc fees <input type="checkbox" id="optional3" onclick="optionalfee()" /> <input type="number" id="optional-fee3" name="mfees"><br><br>
Include Olympiad fees <input type="checkbox" id="optional4" onclick="optionalfee()" /> <input type="number" id="optional-fee4" name="ofees"><br><br>
Optional fees total<input type="number" id="toptional" name="toptional" class="toptional" readonly>
<input type="button" onclick="optionalfee()" value="sum" />
</body>
</html>