当前位置: 代码迷 >> JavaScript >> 自动累加checked的checkbox的value解决方法
  详细解决方案

自动累加checked的checkbox的value解决方法

热度:166   发布时间:2012-03-24 14:00:46.0
自动累加checked的checkbox的value
DOM:


<form>
<table>
<tbody>
<tr>
<td> sample </td>
<td   class= "trade_price "> 100.80 </td>
<td> <input   type= "checkbox "   name= "trade_picker "/> </td>
</tr>
<tr>
<td> sample </td>
<td   class= "trade_price "> 49.72 </td>
<td> <input   type= "checkbox "   name= "trade_picker "/> </td>
</tr>
<tr>
<td> sample </td>
<td   class= "trade_price "> 122.50 </td>
<td> <input   type= "checkbox "   name= "trade_picker "/> </td>
</tr>
<tr>
<td> sample </td>
<td   class= "trade_price "> 95.00 </td>
<td> <input   type= "checkbox "   name= "trade_picker "/> </td>
</tr>
<tr>
<td> sample </td>
<td   class= "trade_price "> 8.00 </td>
<td> <input   type= "checkbox "   name= "trade_picker "/> </td>
</tr>
</tbody>
</table>
<p> total: <input   type= "text "   id= "total_price "   value= "0.00 "/> </p>
<button> submit </button>
</form>

在每次改变.trade_picker的时候,#total_price的value会重新累加,请高手赐教。

------解决方案--------------------
<input type= "checkbox " name= "trade_picker " onchange= "Add(要相加的值,this) "/>

<script>
function Add(value,cb)
{
var price=document.getElementById( 'total_price ');
if(cb.checked)
price.value=parseInt(price.value)+parseInt(value);
else
price.value=parseInt(price.value)-parseInt(value);
}
</script>
------解决方案--------------------
我只能写成这样了。有点不对 。。。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN " "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns= "http://www.w3.org/1999/xhtml ">
<head>
<meta http-equiv= "Content-Type " content= "text/html; charset=gb2312 " />
<title> 无标题文档 </title>

<script language= "javascript ">
function add()
{
var src=event.srcElement;
var total=document.getElementById( "total_price ");


if (src.checked)
{
total.value=parseFloat(total.value)+parseFloat(src.parentNode.previousSibling.innerHTML);
}else{
total.value=parseFloat(total.value)-parseFloat(src.parentNode.previousSibling.innerHTML);
}
}

function onload()
{
var inputarr=document.getElementsByName( "trade_picker ");
for (var i=0;i <inputarr.length;i++ )
{
inputarr[i].attachEvent( "onclick ",add);
}
}
</script>
</head>

<body onload= "onload() ">
<form>
<table>
<tbody>
<tr>
<td> sample </td>
<td class= "trade_price "> 100.80 </td>
<td> <input type= "checkbox " name= "trade_picker "/> </td>
  相关解决方案