Javascript添加复选框值点击


Javascript add checkbox values on click

我使用这个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>

然后我有PHP/HTML代码,从数据库中的表中进行选择,并添加复选框,其值作为数据库中的float字段。

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

由于某些原因,当做减法时,显示奇数并且不正确。

我在这里创建了一个小提琴,这样你也可以看到html: http://jsfiddle.net/j08691/kHxmG/4/

我该怎么做才能让它正常工作?

***jsFiddle Demo***

我建议你阅读这些帖子:

    JavaScript浮点数问题的优雅解决方案
  • JavaScript的浮点数学坏了吗?

写一个函数帮你校正数字:

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

别忘了检查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;
    }
}