2017-01-16 42 views
2
$(document).ready(function() { 
    $(':checkbox').change(function() {   
     $('input:checkbox:checked').filter(function() { 
      var sum = 0;   
      var Something = parseFloat($(this).closest('tr').find('td:eq(2)').text()) + sum; 
      var value = Something; 
      alert(Something); 
      $('#total').html(value); 
     }); 
    }); 
}); 
<table class="table table-bordered" id="echotable"> 
    <tr> 
     <th class="field-label col-xs-1 primary">ID</th> 
     <th class="field-label col-xs-5 primary">Name Of Service</th> 
     <th class="field-label col-xs-3 primary">Price</th> 
     <th class="field-label col-xs-3 primary">Total</th> 
    </tr> 
    <?php foreach($echo_details as $post){?> 
     <tr class="active" id="myrow"> 
      <td class="field-label col-xs-1 primary"><?php echo $post->echo_id;?></td> 
      <td class="field-label col-xs-5 primary"><?php echo $post->echo_scan;?></td>  
      <td class="field-label col-xs-3 primary" id="price"><?php echo $post->price;?></td> 
      <td class="field-label col-xs-3 primary"><input type="checkbox" id="myCheckbox" /></td> 
     </tr> 
    <?php }?> 
    <tr> 
     <td colspan="3" class="total"><strong>TOTAL</strong></td> 
     <td id="total"></td> 
    </tr> 

我動態從數據庫中獲取的值。當用戶選擇多個複選框時,我將獲得所有價格值。現在我需要添加所有的價格值,並且需要顯示總成本。我怎樣才能做到這一點?動態地添加所述多個所選擇的值,並且計算總

enter image description here

+0

在'foreach'循環中的HTML是創建具有相同'id'屬性,這是使你的HTML無效的多個元素。你應該改變'價格'和'myCheckbox'來代替使用類 –

回答

2

您的邏輯是不太正確的。您需要使用each()來圈選複選框,而不是filter()。您還需要在循環外部定義sum,並在循環結束時設置「總計」tdhtml()之前,在每次迭代中添加它。最後請注意,您在總數td元素上設置了class,而不是id,因此您應該使用.total而不是#total來選擇它。試試這個:

$(':checkbox').change(function() { 
 
    var sum = 0; 
 
    $('input:checkbox:checked').each(function() { 
 
    sum += parseFloat($(this).closest('tr').find('td:eq(2)').text()); 
 
    }); 
 
    $('.total').html(sum); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
    <th>ID</th> 
 
    <th>Name Of Service</th> 
 
    <th>Price</th> 
 
    <th>Total</th> 
 
    </tr> 
 
    <tr> 
 
    <td>1</td> 
 
    <td>Echo</td> 
 
    <td>1000</td> 
 
    <td><input type="checkbox" /></td> 
 
    </tr> 
 
    <tr> 
 
    <td>2</td> 
 
    <td>Fetal Echo</td> 
 
    <td>1500</td> 
 
    <td><input type="checkbox" /></td> 
 
    </tr> 
 
    <tr> 
 
    <td colspan="3">TOTAL</td> 
 
    <td class="total">0</td> 
 
    </tr> 
 
</table>

+0

非常感謝你...它的工作.. – user5370838

+0

是啊當然..我奮鬥了很多,以獲得解決方案.. – user5370838