Sum Checked CheckBoxes值

时间:2012-05-12 22:06:57

标签: javascript jquery playframework

我正在使用Play框架和jquery mobile并尝试对已选中复选框的自定义标记值求和,但我无法管理它。这是一些代码;

<form  action="@{Waiter.payAServing()}" method="POST">
<div class="boxes"> 
#{list items:servs, as:'serving'}   
    <fieldset data-role="fieldcontain"> 
        <div class="ui-block-a">
        <input onclick="MySum()" type="checkbox" name="item" id="checkbox-${serving_index}" value="${serving.id}" to="${serving.item.price*serving.amount}" />
        <label for="checkbox-${serving_index}">${serving.item.title} &nbsp; &nbsp; </label>
        </div>

        <div class="ui-block-b"><h2><center>  &nbsp; &nbsp; ${serving.item.price*serving.amount} TL &nbsp;</center></h2></div>          

        <div class="ui-block-c"><h2> ${serving.amount} </h2></div>


</fieldset>     
    #{/list}
</div>
<input type="hidden" name="rid" id="rid" value="${rID}" /><br />

<input type="submit" value="Pay!" />
</form> 

<div class="result"></div>

<script type="text/javascript" charset="${_reponse_encoding}">
function MySum() {

alert(0);

var selectedCustomValue = document.getElementById("checkbox-1").getAttribute("to");

var sum = 0;

alert(selectedCustomValue); 
}

</script>

如何使用jquery或纯javascript对已检查复选框的值求和?

1 个答案:

答案 0 :(得分:2)

试试这个: jQuery版本:

function MySum(){
    var totalSum = 0;
    $("input:checked[name='item']").each(function(index, el){
        totalSum += parseFloat(el.value);
    });
    return totalSum;
}

另外,要将click处理程序绑定到复选框,请使用此内容替换为内联样式:

$(function(){
  $("[name='item']").click(MySum);
});

要获得属性的总和,请尝试以下方法:

function MySum(){
    var totalSum = 0;
    $("input:checked[name='item']").each(function(index, el){
        totalSum += parseFloat($(el).attr("to"));
    });
    return totalSum;
}

更好的方法是在标记中使用data- *属性,如:

<input type="checkbox" 
       name="item" 
       id="checkbox-${serving_index}" 
       value="${serving.id}" 
       data-to="${serving.item.price*serving.amount}" />

,MySum函数将是:

function MySum(){
    var totalSum = 0;
    $("input:checked[name='item']").each(function(a, b){
        totalSum += parseFloat($(b).data("to"));
    });
    return totalSum;
}