如果选中了带有id ='paysms'的复选框,我会得到一些问题,将所有元素加上id ='value',否则默认值。
这是代码。
<table class='table'>
<tr>
<th width='80%'>some things</th>
<th width='20%'>price (usd)</th>
</tr>
<tr>
<td width='80%'>thing1</td>
<td width='20%' id='value'>1.00</td>
</tr>
<tr>
<td width='80%'>thing2</td>
<td width='20%' id='value'>2.00</td>
</tr>
<tr>
<td width='80%'>thing3</td>
<td width='20%' id='value'>3.00</td>
</tr>
<tr>
<td width='80%'>thing4</td>
<td width='20%' id='value'>15.00</td>
</tr>
<tr>
<td width='80%' style='border: none; background: none;'></td>
<td width='20%'><label><input id='paysms' type='checkbox'> sms</label></td>
</tr>
</table>
答案 0 :(得分:1)
ID必须唯一,您应该使用类,请尝试以下操作:
<table class='table'>
<tr>
<th width='80%'>some things</th>
<th width='20%'>price (usd)</th>
</tr>
<tr>
<td width='80%'>thing1</td>
<td width='20%' class='value'>1.00</td>
</tr>
<tr>
<td width='80%'>thing2</td>
<td width='20%' class='value'>2.00</td>
</tr>
<tr>
<td width='80%'>thing3</td>
<td width='20%' class='value'>3.00</td>
</tr>
<tr>
<td width='80%'>thing4</td>
<td width='20%' class='value'>15.00</td>
</tr>
<tr>
<td width='80%' style='border: none; background: none;'></td>
<td width='20%'><label><input id='paysms' type='checkbox'> sms</label></td>
</tr>
</table>
<p id='result'><p>
jQuery的:
$('#paysms').change(function() {
if (this.checked) {
var vals = 0;
$('.value').each(function() {
vals += parseInt($(this).text(), 10)
})
$('#result').text(vals)
} else {
$('#result').text("")
}
})
答案 1 :(得分:1)
undefined的回答似乎并不完全符合您的要求(根据我的理解)。我认为你现在明白了ID必须是唯一的,所以继续使用javascript:
$('#paysms').change(function() {
if ($(this).is(":checked")) {
$(".value").each(function() {
$(this).html(parseInt($(this).html()) + 1 + ".00");
});
} else {
$(".value").each(function() {
$(this).html(parseInt($(this).html()) - 1 + ".00");
});
}
});
和小提琴:http://jsfiddle.net/EwEZK/3/
如果你想要除.00以外的十进制值,则需要修改。
答案 2 :(得分:0)
将id='value'
更改为class='value'
。
$(document).ready(function(){
var price = 0; //default value
$('#paysms').change(function(){
if ($(this).is(':checked')){
$('.value').each(function(){
price += parseFloat($(this).html());
});
} else {
price = 0; // back to default
}
});
});