选中/取消选中所有复选框并添加值

时间:2016-05-24 09:47:38

标签: javascript jquery

我需要为每套图书设置选中/取消选中所有框。它还应该添加总价格和重量。到目前为止,我只能检查每个方框,并且它添加的值很好,但只要我添加一个功能来检查所有方框,一切都停止工作。

//check all function (commented it because it does not work)

//$("#checkAll").change(function () {
//$("input:checkbox").prop('checked', $(this).prop("checked"));
//});


// add weight and price
var inputs = document.getElementsByClassName('sum'),
    totalElement = document.getElementById('payment-total'),
    weightElement = document.getElementById('payment-weight'),
    totalPrice = 0,
    totalWeight = 0;


for (var i = 0; i < inputs.length; i++) {
  inputs[i].onchange = function() {
    if (this.checked) {
      totalPrice += parseFloat(this.value);
      totalWeight += parseFloat(this.getAttribute('Bweight'));
    } else {
      totalPrice -= parseFloat(this.value);
      totalWeight -= parseFloat(this.getAttribute('Bweight'));
    }

    totalElement.innerHTML = totalPrice.toFixed(2);
    weightElement.innerHTML = totalWeight.toFixed(2);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><label><input type="checkbox" id="checkAll"/> Check all Set A</label></p>
<fieldset>
  <legend>Set A Books</legend> 
  <input value="300" type="checkbox" bweight=".500" id="ENG101" class="sum" data-toggle="checkbox"> English
  <input value="500" type="checkbox" bweight=".330" id="SCI101" class="sum" data-toggle="checkbox"> Science
  <input value="755" type="checkbox" bweight=".633" id="CLE101" class="sum" data-toggle="checkbox"> Christian Living
</fieldset>

<p><label><input type="checkbox" id="checkAll"/> Check all Set B</label></p>
<fieldset>
  <legend>Set B Books</legend> 
  <input value="245" type="checkbox" bweight=".845" id="ENG202" class="sum" data-toggle="checkbox"> English
  <input value="534" type="checkbox" bweight=".734" id="SCI202" class="sum" data-toggle="checkbox"> Science
  <input value="623" type="checkbox" bweight=".257" id="CLE202" class="sum" data-toggle="checkbox"> Christian Living
  <input value="954" type="checkbox" bweight=".845" id="MAT101" class="sum" data-toggle="checkbox"> Math
</fieldset>
<p></p>
<div class="card-charge-info">
  Weight <span id="payment-weight">0</span>
</div>
<div class="card-charge-info">
  Price <span id="payment-total">0</span>
</div>

我需要让它以某种方式工作,当选择检查所有时,无论是否选中了单个框,它​​都应该添加总价格和重量。我非常感谢你的帮助,因为我已经坚持了好几天了。谢谢!

4 个答案:

答案 0 :(得分:0)

HTML代码

<p>
                    <label><input onclick="CheckAll('group1', this);" type="checkbox" id="checkAll" /> Check all Set A</label>
                </p>
                <fieldset id="group1">
                    <legend>Set A Books</legend>
                    <input value="300" type="checkbox" bweight=".500" id="ENG101" class="sum" data-toggle="checkbox"> English
                    <input value="500" type="checkbox" bweight=".330" id="SCI101" class="sum" data-toggle="checkbox"> Science
                    <input value="755" type="checkbox" bweight=".633" id="CLE101" class="sum" data-toggle="checkbox"> Christian Living
                </fieldset>

                <p><label><input onclick="CheckAll('group2', this);" type="checkbox" id="checkAll" /> Check all Set B</label></p>
                <fieldset id="group2">
                    <legend>Set B Books</legend>
                    <input value="245" type="checkbox" bweight=".845" id="ENG202" class="sum" data-toggle="checkbox"> English
                    <input value="534" type="checkbox" bweight=".734" id="SCI202" class="sum" data-toggle="checkbox"> Science
                    <input value="623" type="checkbox" bweight=".257" id="CLE202" class="sum" data-toggle="checkbox"> Christian Living
                    <input value="954" type="checkbox" bweight=".845" id="MAT101" class="sum" data-toggle="checkbox"> Math
                </fieldset>
                <p></p>
                <div class="card-charge-info">
                    Weight <span id="payment-weight">0</span>
                </div>
                <div class="card-charge-info">
                    Price <span id="payment-total">0</span>
                </div>

Java脚本代码

var inputs = document.getElementsByClassName('sum'),
totalElement = document.getElementById('payment-total'),
weightElement = document.getElementById('payment-weight'),
totalPrice = 0,
totalWeight = 0;


for (var i = 0; i < inputs.length; i++) {
    inputs[i].onchange = function () {
        if (this.checked) {
            totalPrice += parseFloat(this.value);
            totalWeight += parseFloat(this.getAttribute('Bweight'));
        } else {
            totalPrice -= parseFloat(this.value);
            totalWeight -= parseFloat(this.getAttribute('Bweight'));
        }

        totalElement.innerHTML = totalPrice.toFixed(2);
        weightElement.innerHTML = totalWeight.toFixed(2);
    }
}

function CheckAll(divId, sourceCheckbox) {
    divElement = document.getElementById(divId);
    inputElements = divElement.getElementsByTagName('input');
    for (i = 0; i < inputElements.length; i++) {
        if (inputElements[i].type != 'checkbox')
            continue;

        inputElements[i].checked = sourceCheckbox.checked;

        if (sourceCheckbox.checked) {
            totalPrice += parseFloat(inputElements[i].value);
            totalWeight += parseFloat(inputElements[i].getAttribute('Bweight'));
        } else {
            totalPrice -= parseFloat(inputElements[i].value);
            totalWeight -= parseFloat(inputElements[i].getAttribute('Bweight'));
        }
        totalElement.innerHTML = totalPrice.toFixed(2);
        weightElement.innerHTML = totalWeight.toFixed(2);
    }
}

答案 1 :(得分:0)

试试这个:

$("#checkAll").change(function() {
            $(':checkbox').prop('checked', true); //for check all checkboxes
            $(':checkbox').prop('checked', false); //for uncheck all checkboxes
        });

答案 2 :(得分:0)

请检查此代码

$(document).ready(function(){
			
  $("#AllsetA").change(function(){
    $(".setA").prop('checked', $(this).prop("checked"));
    changeval();
  });
  $("#AllsetB").change(function(){
    $(".setB").prop('checked', $(this).prop("checked"));
    changeval();
  });
  $(".sum").change(function(){
    changeval();
  });
  var changeval = function() {
    var  totalPrice = 0,totalWeight = 0;
    var	count=0;
    $( ".sum" ).each(function( index ) {

      if(this.checked) {

        totalPrice += parseFloat(this.value);
        totalWeight += parseFloat(this.getAttribute('Bweight'));
        count++;
      }
    });
    if(count<=0)
    {
      totalPrice=totalWeight=0;
    }
    $("#payment-weight").html(totalWeight);
    $("#payment-total").html(totalPrice);
  }
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><label><input type="checkbox" class="checkAll" id="AllsetA"/> Check all Set A</label></p>
<fieldset>
  <legend>Set A Books</legend> 
  <input value="300" type="checkbox" bweight=".500" id="ENG101" class="sum setA" data-toggle="checkbox"> English
  <input value="500" type="checkbox" bweight=".330" id="SCI101" class="sum setA" data-toggle="checkbox"> Science
  <input value="755" type="checkbox" bweight=".633" id="CLE101" class="sum setA" data-toggle="checkbox"> Christian Living
</fieldset>

<p><label><input type="checkbox" class="checkAll" id="AllsetB"/> Check all Set B</label></p>
<fieldset>
  <legend>Set B Books</legend> 
  <input value="245" type="checkbox" bweight=".845" id="ENG202" class="sum setB" data-toggle="checkbox"> English
  <input value="534" type="checkbox" bweight=".734" id="SCI202" class="sum setB" data-toggle="checkbox"> Science
  <input value="623" type="checkbox" bweight=".257" id="CLE202" class="sum setB" data-toggle="checkbox"> Christian Living
  <input value="954" type="checkbox" bweight=".845" id="MAT101" class="sum setB" data-toggle="checkbox"> Math
</fieldset>
<p></p>
<div class="card-charge-info">
  Weight <span id="payment-weight">0</span>
</div>
<div class="card-charge-info">
  Price <span id="payment-total">0</span>
</div>

答案 3 :(得分:0)

我会这样做。它看起来似乎不必要地使用循环,但考虑到少量的控件,这不是问题,它使代码更容易阅读。

代码支持checkAll功能的输入更新,反之亦然。

// Shorter querySelectorAll that returns a real array.
function select(selector, parent){
  return Array.from((parent||document).querySelectorAll(selector));  
}

var inputs = select('.sum'),
    totalElement = document.getElementById('payment-total'),
    weightElement = document.getElementById('payment-weight');

function sumUpdate(){
  totalElement.innerHTML = inputs.reduce(function(result, input){
    return result + (input.checked ? parseFloat(input.value) : 0);
  }, 0).toFixed(2);
  weightElement.innerHTML = inputs.reduce(function(result, input){
    return result + (input.checked ? parseFloat(input.getAttribute('bweight')) : 0);
  }, 0).toFixed(2);
}

// Update the sums in function on input change.
inputs.forEach(function(input){
  input.addEventListener("change", sumUpdate);
});

select(".checkAll").forEach(function(checkAll){
  var targetFieldSet = document.getElementById(checkAll.getAttribute("data-target-set"));
  var targetInputs = select(".sum", targetFieldSet);
  
  // Update checkAll in function of the inputs on input change.
  targetInputs.forEach(function(input){
    input.addEventListener("change", function(){
      checkAll.checked = input.checked && targetInputs.every(function(sibling){
        return sibling.checked;
      });
    });  
  });
  
  // Update the inputs on checkall change, then udpate the sums.
  checkAll.addEventListener("change", function(){
    targetInputs.forEach(function(input){
      input.checked = checkAll.checked;
    });
    sumUpdate();
  });  
});
<p><label><input type="checkbox" class="checkAll" data-target-set="setA"/> Check all Set A</label></p>
<fieldset id="setA">
  <legend>Set A Books</legend> 
  <input value="300" type="checkbox" bweight=".500" id="ENG101" class="sum" data-toggle="checkbox"> English
  <input value="500" type="checkbox" bweight=".330" id="SCI101" class="sum" data-toggle="checkbox"> Science
  <input value="755" type="checkbox" bweight=".633" id="CLE101" class="sum" data-toggle="checkbox"> Christian Living
</fieldset>

<p><label><input type="checkbox" class="checkAll" data-target-set="setB"/> Check all Set B</label></p>
<fieldset id="setB">
  <legend>Set B Books</legend> 
  <input value="245" type="checkbox" bweight=".845" id="ENG202" class="sum" data-toggle="checkbox"> English
  <input value="534" type="checkbox" bweight=".734" id="SCI202" class="sum" data-toggle="checkbox"> Science
  <input value="623" type="checkbox" bweight=".257" id="CLE202" class="sum" data-toggle="checkbox"> Christian Living
  <input value="954" type="checkbox" bweight=".845" id="MAT101" class="sum" data-toggle="checkbox"> Math
</fieldset>
<p></p>
<div class="card-charge-info">
  Weight <span id="payment-weight">0</span>
</div>
<div class="card-charge-info">
  Price <span id="payment-total">0</span>
</div>