doupingmao1903 2013-05-10 18:54
浏览 30
已采纳

Javascript在点击时添加复选框值

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?

  • 写回答

2条回答 默认 最新

  • dongqiao1964 2013-05-10 19:33
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析