js GridView 实现自动计算操作代码

  注意下面的代码,需要加载jquery所以请大家自行到官方网站下载最新版本。

  

复制代码 代码如下:

  <!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>

  <title>js操作GridView,实现自动计算</title>

  <style type="text/css"><!--

  table,tr,td{text-align:center;}

  input{width:50px;text-align:center;}

  --></style><style type="text/css" bogus="1"> table,tr,td{text-align:center;}

  input{width:50px;text-align:center;}

  </style>

  <script type="text/javascript" src="http://dl.glzy8.com/img/jslib/jquery/jquery-1.2.6.pack.js"></script>

  <script type="text/javascript"><!--

  //全局

  var tbl;

  //改变总金额与总数量

  function setTotal(){

  var totalAmount=0;//总金额

  var totalCount=0;//总数量

  if(tbl!=null&&tbl.rows.length>2)//表头占一行

  {

  for(var n=1;n<tbl.rows.length-1;n++)//rows数组是从0开始,表足占一行

  {

  //总数量

  if(!isNaN(tbl.rows[n].cells[2].childNodes[0].value))

  {

  totalCount+=Number(tbl.rows[n].cells[2].childNodes[0].value);

  }

  //总金额

  if(!isNaN(tbl.rows[n].cells[3].innerText))//判断是不是数字

  {

  totalAmount+=Number(tbl.rows[n].cells[3].innerText);

  }

  }

  }

  tbl.rows[tbl.rows.length-1].cells[2].innerText=totalCount;

  tbl.rows[tbl.rows.length-1].cells[3].innerText=totalAmount;

  }

  //单价改变,根据行号找到同一行的数量与金额,

  //这些值可以用index='<%#Container.DataItemIndex %>'绑定

  function fPrice(rowId,val){

  tbl.rows[Number(rowId)].cells[3].innerText=

  Number(val)* Number(tbl.rows[Number(rowId)].cells[2].childNodes[0].value);

  }

  //数量改变

  function fCount(rowId,val){

  tbl.rows[Number(rowId)].cells[3].innerText=

  Number(val)* Number(tbl.rows[Number(rowId)].cells[1].childNodes[0].value);

  }

  //限制只能输入数字

  function checknum()

  {

  if((event.keyCode>=48&&event.keyCode<=57)||event.keyCode==8||(event.keyCode>=96&&event.keyCode<=105)

  ||event.keyCode==46||event.keyCode==37||event.keyCode==39||event.keyCode==190||event.keyCode==110)

  {

  event.returnValue=true;

  }

  else

  {

  event.returnValue=false;

  }

  }

  jQuery(function(){

  //初始化table

  //tbl=document.getElementById("GridView1");

  tbl=$("#GridView1").get(0);//返回DOM对象

  //对input键盘限制

  jQuery("input").keydown(function(){

  checknum();

  }).keyup(function(){

  setTotal();

  });

  });

  // --></script>

  </head>

  <body>

  <table id="GridView1" border="1">

  <tr>

  <td>编号</td>

  <td>单价</td>

  <td>数量</td>

  <td>金额</td>

  </tr>

  <tr>

  <td>1</td>

  <td><input type="text" onkeyup="fPrice(1,this.value);" /></td>

  <td><input type="text" onkeyup="fCount(1,this.value);" /></td>

  <td></td>

  </tr>

  <tr>

  <td>2</td>

  <td><input type="text" onkeyup="fPrice(2,this.value);" /></td>

  <td><input type="text" onkeyup="fCount(2,this.value);"/></td>

  <td></td>

  </tr>

  <tr>

  <td>合计</td>

  <td></td>

  <td></td>

  <td></td>

  </tr>

  </table>

  </body>

  </html>