2017-10-09 82 views
0

在這種while循環我有值的列表:總金額上線點擊複選框

<?php 
while($row_list = mysqli_fetch_array($res_list)) { 
    echo '<input type="checkbox" class="cost" value="'.$row_list['bedrag_incl'].'">'.$row_list['bedrag_incl']; 
} ?> 

當我點擊複選框,我需要點擊的項目總數達到了概括起來就是它的總並顯示在這裏:

<input type="text" id="bedragen_selected" name="bedragen_selected" value="" size="5" style="text-align:right;background-color: #e7e7e9" readonly="readonly" /> 

要做到這一點我有這樣的JS代碼:

<script type="text/javascript"></script> 
var sum = 0; 

$('.cost').live('click',function() 
{ 
    if($(this).is(':checked')) 
    { 
     sum = sum + parseFloat($(this).val()); 
    } 
    else 
    { 
     sum = sum - parseFloat($(this).val()); 
    } 
    $('#bedragen_selected').val(sum); 
} 
); 
</script> 

對於某些[R eason沒有顯示結果,甚至給出了錯誤。 有什麼建議嗎?

+1

你檢查是否'$( '成本 ')。住(' 點擊',()的函數 {}'被稱爲? –

+1

我換成你的點擊函數使用'$(document).on('click','.cost',function(){'和[它正在正常工作](https://jsfiddle.net/g4Lxth2f/) –

回答

0

嘗試這樣,

$(".cost").change(function(){ 
    calculate(); 
}); 


function calculate(){ 
    var sum = 0; 

    $("input[type=checkbox]:checked").each(function(){ 
     sum += parseInt($(this).attr("value")); 
    }); 

    alert(sum); 
} 
2

希望這有助於你。

$(document).on('click', '.cost', function(event) { 
    var total = 0; 
    $('.cost:checked').each(function(){ 
     total += isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val()); 
    }); 
    $("#bedragen_selected").val(total); 
}); 

$(document).on('click', '.cost', function(event) { 
 
    var total = 0; 
 
    $('.cost:checked').each(function(){ 
 
     total += isNaN(parseFloat($(this).val())) ? 0 : parseFloat($(this).val()); 
 
    }); 
 
    $("#bedragen_selected").val(total); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> 
 
<input type="checkbox" class="cost" value="1">1<br> 
 
<input type="checkbox" class="cost" value="2">2<br> 
 
<input type="checkbox" class="cost" value="3">3<br> 
 
<input type="checkbox" class="cost" value="4">4<br> 
 
<input type="text" id="bedragen_selected" name="bedragen_selected" value="" size="5" style="text-align:right;background-color: #e7e7e9" readonly="readonly" />