Reputation: 1520
I have an list with values which is generated by an database query. I want to see the total sum of values that been selected (by an checkbox) by the user.
Code for checkbox:
<?php
$i = -1;
while ($row = mysql_fetch_array($res))
{
$i++;
?>
echo '<table>
<tr>
<td><input type="checkbox" onclick="bedrag_optellen(this, <?php echo $i ?>);" value= "'.$row['bedrag_incl'].'"></td>
<td>€ '.number_format($row['bedrag_incl'], 2, ',', ' ').'</td>
</tr>
</table>';
}
?>
Code for output field:
<table>
<tr>
<td width="51"><input type="text" id="bedragen_selected" name="bedragen_selected" value="" size="10" style="text-align:right;background-color: #e7e7e9" readonly="readonly" /></td>
</tr>
</table>
JavaScript
<script type="text/javascript"</script>
function bedrag_optellen(checkbox, nr)
{
var i, totaal = 0;
var elems = document.getElementsByName('bedrag_optellen[]');
var l = elems.length;
for(i=0; i<l; i++)
{
if(formElement['bedrag_optellen[]'][i].checked = true)
{
totaal += parseFloat(elems[i].value) || 0;
}
document.getElementById('bedragen_selected').value = totaal.toFixed( 2 );
}
}
</script>
The code is not working, also there is no error given.
Is there anyone to help me out?
https://jsfiddle.net/fawavmbo/
Upvotes: 1
Views: 1010
Reputation: 4453
Check out this fiddle.
I have used jQuery for the simplicity it provides.
I made the following changes:
cost
to the checkboxes.onClick
attribute.For the code to work in you system, add the code below to your <head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is the snippet.
HTML
<table>
<tr>
<td><input class='cost' type="checkbox" value= "8"></td>
<td>€ 8</td>
</tr>
<tr>
<td><input class='cost' type="checkbox" value= "3"></td>
<td>€ 3</td>
</tr>
<tr>
<td><input class='cost' type="checkbox" value= "19"></td>
<td>€ 19</td>
</tr>
<tr>
<td><input class='cost' type="checkbox" value= "2"></td>
<td>€ 2</td>
</tr>
<tr>
<td><input class='cost' type="checkbox" value= "15"></td>
<td>€ 15</td>
</tr>
<tr>
<td><input class='cost' type="checkbox" value= "12"></td>
<td>€ 12</td>
</tr>
</table>
<table>
<tr>
<td width="51"><input type="text" id="bedragen_selected" name="bedragen_selected" value="" size="10" style="text-align:right;background-color: #e7e7e9" readonly="readonly" /></td>
</tr>
</table>
JS
var sum = 0;
$('.cost').click(function() {
if($(this).is(':checked')) {
sum = sum + parseInt($(this).val());
} else {
sum = sum - parseInt($(this).val());
}
$('#bedragen_selected').val(sum);
});
Upvotes: 1