0

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?

Expedito
  • 7,771
  • 5
  • 30
  • 43

2 Answers2

0
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;
    }
}
Orangepill
  • 24,500
  • 3
  • 42
  • 63
  • try checking the top one, then the 2nd one, then uncheck the top one and look at the number in the total box - this is what was happening to me before - its really confusing me now lol –  May 10 '13 at 19:11
  • the link posted by @NullPointerException has the good description and solution for this issue. – Orangepill May 10 '13 at 19:14
  • ive tried doing the sprintf function like sprintf("%.2",thetotal) but still nothing - its not even displaying any values in the textfiedl –  May 10 '13 at 19:26
  • updated to use scaling method to eliminate the floating point math issue. – Orangepill May 10 '13 at 19:36
0

***jsFiddle Demo***

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.

Community
  • 1
  • 1