如何在javascript中正确添加我的结果

问题描述 投票:1回答:1

我有一个小脚本,检查选定的框并对其进行广告。 有些盒子值得两个,有些值得一个。 我可以让它们加起来,但前提是我先选择两个指针中的一个,反之亦然。

HTML

<div class="checkbox pmmargin">
    <label><input type="checkbox" value="" class="one">Some blah blah text</label>
</div>
<div class="checkbox pmmargin">
    <label><input type="checkbox" value="" class="two">Text</label>
</div>
<div class="checkbox pmmargin">
    <label><input type="checkbox" value="" class="one">text</label>
</div> 

Javascript

$(".two").change(function() {
    var classes = $("input[type='checkbox'].two:checked").map(function() {
        return this.className;
    }).get().length * 2;
            document.getElementById("program_management2").innerHTML = " Score:" + " " + Math.floor(classes) ;

    $(".one").change(function() {
    var classes2 = $("input[type='checkbox'].one:checked").map(function() {
        return this.className;
    }).get().length;

            document.getElementById("program_management").innerHTML = " Score:" + " " + Math.floor(classes2 + classes) ;

});  
    });
javascript jquery html
1个回答
1
投票

如果您只想添加每个已选中复选框的值,则应使用value属性。

由于该值是字符串,因此您必须将其解析为整数以在添加中使用它。

    $("input[type='checkbox']").click(function(){
     var result = 0;
        $("input[type='checkbox']:checked").each(function(){
          result += parseInt($(this).val());
     });
        $("#total").html(result);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


    <input type="checkbox" value="1">This box value is 1<br>
    <input type="checkbox" value="2">This box value is 2<br>
    <input type="checkbox" value="5">This box value is 5<br>
    <br>
    <br>
    The checked total is: <span id="total">0</span>

编辑

我添加了一个“检查类”计数。

$("input[type='checkbox']").click(function(){
    var result = 0;
    var classOne = 0;
    var classTwo = 0;

    $("input[type='checkbox']:checked").each(function(){
        result += parseInt($(this).val());
        if( $(this).hasClass("one") ){
            classOne++;
        }
        if( $(this).hasClass("two") ){
            classTwo++;
        }
        $("#totalOne").html(classOne);
        $("#totalTwo").html(classTwo);

    });
    $("#total").html(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<input type="checkbox" value="1" class="one">This box value is 1<br>
<input type="checkbox" value="2" class="two">This box value is 2<br>
<input type="checkbox" value="1" class="one">This box value is 1<br>
<input type="checkbox" value="2" class="two">This box value is 2<br>
<input type="checkbox" value="2" class="two">This box value is 2<br>
<br>
<br>
The checked total value is: <span id="total">0</span><br>
Class "one" checked total : <span id="totalOne">0</span><br>
Class "two" checked total : <span id="totalTwo">0</span><br>
© www.soinside.com 2019 - 2024. All rights reserved.