思路:
1、获取被选中checkbox,通过checked属性的状态完成;
2、获取被选中的checkbox的value值;
3、求所有value的和sum;
4、定义span区域存储和sum;
代码如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>表单组件:全选操作</title>
<script type="text/javascript">
function checkAll(index){
var node = document.getElementsByName("all")[index];
var items = document.getElementsByName("item");
for(var i=0; i<items.length; i++){
items[i].checked = node.checked;
}
}
</script>
</head>
<body>
<p></p>
<input type="checkbox" name="all" onclick="checkAll(0)"/>全选<br/>
<input type="checkbox" name="item" value="100"/>商品1<br/>
<input type="checkbox" name="item" value="100"/>商品2<br/>
<input type="checkbox" name="item" value="100"/>商品3<br/>
<input type="checkbox" name="item" value="100"/>商品4<br/>
<input type="checkbox" name="item" value="100"/>商品5<br/>
<input type="checkbox" name="item" value="100"/>商品6<br/>
<input type="checkbox" name="all" onclick="checkAll(1)"/>全选
</body>
</html>
代码如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>购物车显示选中购买物品的总金额</title>
<script type="text/javascript">
function checkAll(index){
var node = document.getElementsByName("all")[index];
var items = document.getElementsByName("item");
for(var i=0; i<items.length; i++){
items[i].checked = node.checked;
}
}
function getSum(){
var items = document.getElementsByName("item");
var sum = 0;
for(var i=0; i<items.length; i++){
if(items[i].checked){
sum += parseInt(items[i].value);
}
}
/*获取单个节点用getElementById
获取节点数组用getElementsById
*/
var spanNode = document.getElementById("sum");
var str = sum + "元";
spanNode.innerHTML = str.fontsize(8);
}
</script>
</head>
<body>
<br/>
<input type="checkbox" name="all" onclick="checkAll(0)"/>全选<br/>
<input type="checkbox" name="item" value="105"/>商品1<br/>
<input type="checkbox" name="item" value="214"/>商品2<br/>
<input type="checkbox" name="item" value="113"/>商品3<br/>
<input type="checkbox" name="item" value="77"/>商品4<br/>
<input type="checkbox" name="item" value="91"/>商品5<br/>
<input type="checkbox" name="item" value="536"/>商品6<br/>
<input type="checkbox" name="all" onclick="checkAll(1)"/>全选<br/>
<input type="button" value="显示总金额" onclick="getSum()"/><span id="sum"></span>
</body>
</html>