如何计算复选框值的总和取决于文本框中的数量

时间:2017-09-20 16:53:02

标签: javascript jquery checkbox

我有下表

<table>
<tr style="background-color: silver;">
    <th>Check it</th>
    <th>Estimate item</th>
    <th>Quantity</th>
    <th>Cost</th>               
</tr>
<tr>
   <td><input type="checkbox" value="450" /></td>
   <td>Remove Tile</td>
   <td><input type="text" value="1"></td>
   <td>$450</td>
</tr>
<tr>
   <td><input type="checkbox" value="550" /></td>
   <td>Remove Tub</td>
   <td><input type="text" value="1"></td>
   <td>$550</td>
</tr>

<p>Calculated Price: $<input type="text" name="price" id="price" disabled /></p>

Table example 我找到了如何计算复选框值的总和:

<script>
        $(document).ready(function () {
            var $inputs = $('input[type="checkbox"]')
            $inputs.on('change', function () {
                var sum = 0;
                $inputs.each(function() {
                   if(this.checked)
                       sum += parseInt(this.value);
                });
                $("#price").val(sum);
            });
        });
</script>

问题是: 如果用户将更新文本框中的数量,我需要更新总数。 我希望它以两种方式工作:检查复选框之前或之后的数量。

因此“成本”列中的值等于复选框值。我不想修改“费用”列。我需要在“textbox with id =”price“textbox。”

的表格底部显示总数

案例: 用户选中了第一个复选框#price应该用450更新。 用户选中了第二个复选框#price should benow 1000。 用户使用第一个复选框将数量更改为2行。现在#price应更新为1450

提前致谢!

3 个答案:

答案 0 :(得分:0)

为了达到这个目的,你应该遍历表体的行,以便使用代码

 $('table tbody tr').each(function() 
 {
     //do something
 });

然后在该鱼巢中找到该复选框。您可以使用$tr.find('input[type="checkbox"]').is(':checked')此代码检查是否已选中该复选框。它将在行中找到一个复选框,它将检查天气是否被检查。

var $columns = $tr.find('td').next('td').next('td');此代码用于检索列数量。

我们调用函数calculateSum()来计算文本框更改事件和复选框更改事件中已检查行的总和。

&#13;
&#13;
$(document).ready(function() {

function calculateSum(){
 var sumTotal=0;
    $('table tbody tr').each(function() {
      var $tr = $(this);

      if ($tr.find('input[type="checkbox"]').is(':checked')) {
          
        var $columns = $tr.find('td').next('td').next('td');
         
         var $Qnty=parseInt($tr.find('input[type="text"]').val());
 var $Cost=parseInt($columns.next('td').html().split('$')[1]);
         sumTotal+=$Qnty*$Cost;
      }
    });

       $("#price").val(sumTotal);
       
}

  $('#sum').on('click', function() {
     
    calculateSum();
  });

  $("input[type='text']").keyup(function() {
     calculateSum();

  });
  
   $("input[type='checkbox']").change(function() {
     calculateSum();

  });



});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="sum" type="button">Calculate</button><br/>

<table>
  <tr style="background-color: silver;">
    <th>Check it</th>
    <th>Estimate item</th>
    <th>Quantity</th>
    <th>Cost</th>
  </tr>
  <tr>
    <td><input type="checkbox" name="chck" value="450" /></td>
    <td>Remove Tile</td>
    <td><input type="text" name="qnty" value="1"></td>
    <td>$450</td>
  </tr>
  <tr>
    <td><input type="checkbox" class="chck" value="550" /></td>
    <td>Remove Tub</td>
    <td><input type="text" name="qnty" value="1"></td>
    <td>$550</td>
  </tr>
  </table>
  
  <p>Calculated Price: $<input type="text" name="price" id="price" disabled /></p>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

<div class="serve" id="service"> 

<form action="" id="roomform" onsubmit="return false">
<div class="order">
<fieldset>
<legend>Tell us where to clean:</legend>
<p>
<input value="30" type="checkbox" id="myCheck" class="sum" name="myCheck" oninput="x.value=parseInt(bedroom.value)*30.00"/>
<label for="sleeping" class="contain">Bedrooms (P30/room) </label> 
<input type="number" id="a" class="room" value="1" min="1" max="20" onchange="calculateTotal()"/>
Total: P <span id="costPrice"> </span
</p>
<p>
<input value="20" type="checkbox" id="myCheck" class="sum" name="myCheck1" onclick="calculateTotal()" />
<label for="sitting" class="contain">Sitting room (P20/room)</label> 
<input type="number" class="room" id="a" value="1" min="1" max="20" />
Total: P <output type="number" ></output> 
</p>
<p>
 <input value="20" type="checkbox" id="myCheck" class="sum" onclick="calculateTotal()" />
 <label class="contain">Dining room (P20/room)</label> 
 <input type="number" class="room" id="a" value="1" min="1" max="20" />
 Total: P <output type="number" ></output>    
 </p>

 <p>
 Extra services:</p>
 <p>
 <input value="15" type="checkbox" id="myCheck" class="sum" onclick="calculateTotal()" />
  <label class="contain">Carpet Cleaning (P 15/room)</label> 
  <input type="number" class="room" id="a" value="0" min="0" max="20" />
Total: P <output type="number" ></output>    
</p>
 <p>
 <input value="3" type="checkbox" id="myCheck" class="sum"   onclick="calculateTotal()" />
 <label class="contain">Window Cleaning (P 3/room)</label> 
<input type="number" class="room" id="a" value="0" min="0" max="20" />
Total: P <output type="number" ></output> 
</p>
<div class="grandPrice" >
 Grand Total Price: P<span id="grandTotal">0</span>
 </div>
 </fieldset>    
 </div>
  </form>
 <script>
 // When a checkbox is clicked
 /*$('#order input[type=checkbox]').click(function() {
// Get user input and set initial variable for the total
inputBox = parseInt($('#a').val());
bedroomPrices = 0;

// If it's checked, add the current value to total

    if($(this).prop('checked'))
    {
        thisValue = parseInt($(this).val());
        bedroomPrices = bedroomPrices + thisValue;
    }

// Output the total checkbox value multipled against user input
$('#costPrice').html(bedroomPrices * inputBox);    
 });*/

 var checkbox = document.getElementsByClassName('sum'),
 inputBox = document.getElementById('a'),
    GrandTotal  = document.getElementById('grandTotal');

 //"(this.checked ? 1 : -1);" this sees if checkbox is checked or unchecked   by adding or subtracting it (1 :-1)
//make sure that each checkbox total is added if its checked
for (var i=0; i < checkbox.length; i++) {
    checkbox[i].onchange = function() {

        var add = this.value * (this.checked ? 1 : -1);

        grandTotal.innerHTML = parseFloat(grandTotal.innerHTML) + add

    }
}

</div>

</body>

答案 2 :(得分:0)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="indent_list">
    <table border="1">
        <thead>
            <tr>
                <th>rate</th>
                <th>quantity</th>
                <th>coltotal</th>
            </tr>
        </thead>
        <body>
            <tr>
                <td><input type="text" id="val" class="rate" value="10"></td>
                <td><input type="text" id="val" class="quantity" value="1"></td>
                <td><input type="text" id="val" class="coltolal" value=""></td>
            </tr>
            <tr>
                <td><input type="text" id="val" class="rate" value="10"></td>
                <td><input type="text" id="val" class="quantity" value="2"></td>
                <td><input type="text" id="val" class="coltolal" value=""></td>

            </tr>
            <tr>
                <td><input type="text" id="val" class="rate" value="10"></td>
                <td><input type="text" id="val" class="quantity" value="2"></td>
                <td><input type="text" id="val" class="coltolal" value=""></td>

            </tr>
        </body>
        <tfoot>
            <tr>
                <th class="rateRow"></th>
                <th class="quantityRow"></th>
            </tr>
            <tr>
                <th colspan="2" class="totalRow"></th>
            </tr>
        </tfoot>
    </table>
</div>

> button

<input type="checkbox" class="btn btn-info checkbox" onclick="calculateCheck()">
<input type="button" class="btn btn-info" onclick="calculate()" value="Calculate">

> script

<script>
    function calculateCheck() {
        var check = $('.checkbox').prop('checked');
        if (check) {
            calculate()
        } else {
            $('.rateRow').text('');
            $('.quantityRow').text('');
            $('.totalRow').text('');
        }
    }
    function calculate() {
        var rateRow = '';
        var quantityRow = '';
        var totalRow = '';
        var rate = 0;
        var quantity = 0;
        var total = 0;

        // alert(quantitycol);
        $('tbody tr').each(function () {
            var ratecol = $('td .rate', this).val();
            var quantitycol = $('td .quantity', this).val();
            var coltotal = ratecol * quantitycol;
            $('td .coltolal', this).val(coltotal);
            // alert(a);
            rate += +$('td .rate', this).val();
            quantity += +$('td .quantity', this).val();
            total = rate * quantity;
           
        });
        rateRow += rate;
        quantityRow += quantity;
        totalRow = total;

        $('.rateRow').text(rateRow);
        $('.quantityRow').text(quantityRow);
        $('.totalRow').text(totalRow);
    }
</script>