【问题标题】:How to calculate total sum of checkbox values depend on quantity in textbox如何计算复选框值的总和取决于文本框中的数量
【发布时间】:2017-09-20 16:53:02
【问题描述】:

我有下表

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

&lt;p&gt;Calculated Price: $&lt;input type="text" name="price" id="price" disabled /&gt;&lt;/p&gt;

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>

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

所以“成本”列中的值等于复选框值。我不想修改“成本”列。我需要在“带有 id="price" 文本框的文本框的表格底部显示总计。

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

提前致谢!

【问题讨论】:

标签: javascript jquery checkbox


【解决方案1】:

要实现这一点,您应该循环遍历表格主体的行,使用代码作为

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

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

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

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

$(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();

  });



});
<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>

【讨论】:

  • 这是预期的输出吗?
  • 感谢您的回复!请看,我已经更新了帖子。
  • @AnatolyPerevera 我还编辑了我的答案。只需浏览一遍,并及时更新您的反馈。
  • 这太棒了 JINO!您能否再添加一项功能:当数量更改以更新文本框“#price”值时。我很感激!!!
  • @AnatolyPerevera 是的,已经完成了。只是将文本框事件更改为 keypres。现在它正在工作。请仔细阅读并提供您的反馈,以了解这是您想要的吗?
【解决方案2】:
<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>

【讨论】:

  • 请在此处添加有意义的问题描述。
【解决方案3】:
<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>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-19
  • 2011-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多