I am using this JavaScript code:
<script>
function add(total, this_chk_bx)
{
var thetotal = form2.thetotal.value;
if(this_chk_bx.checked==true)
{
//add if its checked
form2.thetotal.value = Number(thetotal)+Number(total);
}
else
{
//subtract if its unchecked
form2.thetotal.value = thetotal-total;
}
}
</script>
And then I have PHP/HTML code that selects from a table in a database and adds checkboxes with the values as a float field in the database.
What I'm trying to do is to make it so that when the checkboxes are ticked, it adds the values up and displays them in a text field, and then when they are unchecked, it removes that value from the field.
For some reason, when subtracting, it's displaying odd numbers and incorrectly.
I have created a fiddle here so you can also see the HMTL: http://jsfiddle.net/j08691/kHxmG/4/
Any ideas on what I can do to get it working properly?
I suggest you read this posts:
Write a function to correct the number for you:
function correctNumber(number) {
return (parseFloat(number.toPrecision(12)));
}
And pass your final number to this function:
function add(total, this_chk_bx) {
var thetotal = (form2.thetotal.value * 1);
var total = total * 1;
if (this_chk_bx.checked == true) {
//add if its checked
form2.thetotal.value = correctNumber(thetotal + total);
} else {
//subtract if its unchecked
form2.thetotal.value = correctNumber(thetotal - total);
}
}
Don't forget to check the jsFiddle Demo.
function add(total, this_chk_bx)
{
var thetotal = form2.thetotal.value;
if(this_chk_bx.checked==true)
{
//add if its checked
form2.thetotal.value = ((thetotal*100)+(total*100))/100;
}
else
{
//subtract if its unchecked
form2.thetotal.value = ((thetotal*100)-(total*100))/100;
}
}