douwo4837 2014-08-27 13:34
浏览 48
已采纳

在表单提交之前,JS输出所有已检查输入字段值的总和(仅数字)

I have a form that has input checkboxes like the ones in the example. The js code extracts the number from the checked input values and outputs them one next to eachother. How to I edit the code so that when you check a second input checkbox the output is the sum of the numbers?

This is the PHP form:

<input type="checkbox" onchange="toggleCheckbox(this)" value="abc 1 def" name="1">
<input type="checkbox" onchange="toggleCheckbox(this)" value="abc 2 def" name="2">
<input type="checkbox" onchange="toggleCheckbox(this)" value="abc 3 def" name="3">

The JavaScript i use:

<script type="text/javascript"> 
    function toggleCheckbox(element){
        if (element.checked){
        var number = element.value.replace ( /[^\d.]/g, '' );
        document.getElementById("test").innerHTML += " " + number;
        }
} 
</script>

The HTML field:

<p id="test"></p>
  • 写回答

2条回答 默认 最新

  • dongshan3759 2014-08-27 13:44
    关注

    You could store the accomulated value in a global variable, E.g.:

    var sum = 0;
    
    function toggleCheckbox(element){
            var number = element.value.replace ( /[^\d.]/g, '' );
            if (element.checked)
                sum += Number(number);
            else
                sum -= Number(number);
            document.getElementById("test").innerHTML = sum;
    } 
    

    Demo fiddle : http://jsfiddle.net/lparcerisa/08hLc37a/

    With jQuery, it could be done this way:

    $("input[type=checkbox]").click(function(){
        var sum=0;
        $("input[type=checkbox]:checked").each(function(index){
            sum += Number($(this).val().replace( /[^\d.]/g,''));
        });
        $("#test").html(sum);
    } );
    

    Demo fiddle (jquery) : http://jsfiddle.net/lparcerisa/res4k96j/2/

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?