我有三套複選框(serviceA,B & C)與每個5個複選框,每一組具有相同的類名。獲取選定複選框並添加至總量
我需要計算每個集合的選中複選框,並將它們與a,b,c(每個服務A,B,C的不同值)相乘,並顯示文本框,div或其他內容中所有選擇的總和。
到目前爲止,我得到了預期的結果,它一切正常,但我希望jQuery專家告訴我,如果有更好的方法或者更短或更整潔的方式來編寫代碼。
這裏是我的代碼,也是在jsfiddle:
HTML:
<html>
<body>
serviceA1 <input type="checkbox" name="serviceA1" id="serviceA1" value="1" class="serviceA" /><br />
serviceA2 <input type="checkbox" name="serviceA2" id="serviceA2" value="1" class="serviceA" /><br />
serviceA3 <input type="checkbox" name="serviceA3" id="serviceA3" value="1" class="serviceA" /><br />
serviceA4 <input type="checkbox" name="serviceA4" id="serviceA4" value="1" class="serviceA" /><br />
serviceB1 <input type="checkbox" name="serviceB1" id="serviceB1" value="1" class="serviceB" /><br />
serviceB2 <input type="checkbox" name="serviceB2" id="serviceB2" value="1" class="serviceB" /><br />
serviceB3 <input type="checkbox" name="serviceB3" id="serviceB3" value="1" class="serviceB" /><br />
serviceB4 <input type="checkbox" name="serviceB4" id="serviceB4" value="1" class="serviceB" /><br />
<p>Total<input type="text" name="TotlCost" id="TotalCost" size="10"/></p>
</body>
</html>
的Javascript:
$(document).ready(function() {
$("input:checkbox").click(function(event) {
var total = 0;
var a = 5;
var b = 10;
var c = 8;
var totalA = 0;
var totalB = 0;
var totalC = 0;
$(".serviceA:checkbox:checked").each(function() {
totalA += parseInt($(this).val());
});
$(".serviceB:checkbox:checked").each(function() {
totalB += parseInt($(this).val());
});
$(".serviceC:checkbox:checked").each(function() {
totalC += parseInt($(this).val());
});
total = totalA*a + totalB*b + totalC*c;
if (total == 0) {
$('#TotalCost').val('0');
} else {
$('#TotalCost').val(total);
}
});
});
UPDATE:另外,#TotalCost已經從頁面上的其他選項的值,如何將複選框總數添加到#TotalCost?
新增:應用公認的答案我的代碼後,我現在有一個問題。我的表單上的控件之一是一個選擇:
<select id="symb" class="big" name="symb">
<option value="1#10#6">Basic Personal</option>
<option value="2#20#6">Basic Family</option>
<option value="10#90#12">Advanced Personal</option>
<option value="11#120#12">Advanced Family</option>
</select>
與中間數字中的隔離值是每個選擇的成本。我怎麼能是成本每個用戶進行選擇的時間添加到#cost場?
點上!謝謝,我真的很喜歡這個簡單的想法「如果所有的複選框在給定相同的類別,例如服務和價值參數被更新爲具有增加/減少的值」 – bikey77
請看看我的最新更新,我已經最後增加了一個新問題。謝謝! – bikey77
@ bikey77我想你應該問一個新的問題,你可以回到這個問答。你正在把它變成一個談話,而不是StackOverflow應該如何工作。 – mttrb