使用复选框来确定要汇总的输入框值

时间:2016-09-30 12:04:24

标签: javascript jquery html

我正在尝试编写一些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>

6 个答案:

答案 0 :(得分:1)

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

input#number name指定为corrsponding复选框的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);
    }


})

答案 1 :(得分:1)

  1. 使所有ID都唯一
  2. 使用了类
  3. 添加了缺失的括号
  4. 测试了isNaN的值并为空
  5. 在号码更改时也会更新
  6. 注意我正在使用id的数据属性

    普通JS:

    function optionalfee() {
      var total = 0;
      // get the checked boxes only
      var checks = document.querySelectorAll('.optional:checked');
      for (var i = 0; i < checks.length; ++i) {
        var check = checks[i];
        // 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.onload = function() {
      var checks = document.querySelectorAll(".optional"),
        fees = document.querySelectorAll(".fee");
      for (var i = 0; i < checks.length; 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>

答案 2 :(得分:1)

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>

答案 3 :(得分:1)

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

&#13;
&#13;
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);
}
&#13;
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>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

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

答案 5 :(得分:0)

检查代码

<!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>