Php Javascript在单击时添加复选框值

Php Javascript在单击时添加复选框值,php,javascript,html,Php,Javascript,Html,我正在使用以下JavaScript代码: <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); }

我正在使用以下JavaScript代码:

<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>

功能添加(总计,本次添加)
{
var thetotal=form2.thetotal.value;
if(this_chk_bx.checked==true)
{
//如果选中,则添加
表2.thetotal.value=总数+总数;
}
其他的
{
//如果未选中,则减去
表2.thetotal.value=总计;
}
}
然后我有PHP/HTML代码,它从数据库中的表中进行选择,并在数据库中添加带有浮点字段值的复选框

我试图做的是,当勾选复选框时,它将值相加并显示在文本字段中,然后当它们未选中时,它将从字段中删除该值

由于某些原因,在进行减法运算时,它显示的是奇数和错误的数字

我在这里创建了一个小提琴,因此您也可以看到HMTL:

有什么办法让它正常工作吗?

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;
    }
}
我建议您阅读以下帖子:

编写一个函数为您更正数字:

function correctNumber(number) {
    return (parseFloat(number.toPrecision(12)));
}
并将您的最终号码传递给此函数:

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);
    }
}

不要忘了检查。

您的小提琴坏了。您的问题是因为浮点值。看看这把工作小提琴:试着检查最上面的一把,然后是第二把,然后取消勾选最上面的一把,看看总数框中的数字-这就是我在检查最上面的一把,然后是第二把之前发生的事情,然后取消勾选上面的一个,看看总数框中的数字-这是我以前遇到的情况-现在我真的很困惑,@NullPointerException发布的链接对这个问题有很好的描述和解决方案。我尝试过使用sprintf之类的sprintf函数(“%.2”,总数)但仍然没有——它甚至没有在TextFiedlUpdate中显示任何值,以使用缩放方法消除浮点数学问题。