2012-05-12 116 views
0

我使用的是玩框架和jQuery的移動,並試圖總結自定義標記值的複選框,但我無法管理這一點。這裏是一些代碼;總和檢查複選框值

<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的複選框的值?

回答

2

試試這個: jQuery的版本:

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

還要去複選框使用上,而不是內聯樣式單擊處理程序綁定:

$(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; 
} 

一個更好的方法是使用數據 - *在你的M屬性分配arkup像:

<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; 
} 
+0

在這種功能的是誰? b誰? :)當我嘗試它的總是顯示給我10,但我想要得到的總和「的」值... –

+0

更新後得到的總和。 'a'是數組中元素的索引,'b'是元素。檢查這個鏈接的更多信息:http://api.jquery.com/each/ – Chandu

+0

也是數據不是整數,我可以使用parseFloat? –