在大多数商城都有这样的功能,当输入商品数量和商品的单价,就会自动计算出来商品的总价格,非常的人性化,省却了用户不少时间,下面是一段类似的代码实例,希望能够给大家带来一定的帮助。

代码实例如下:
   [ 其他 ] 运行代码    下载代码
<!DOCTYPE html> 
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.51qianduan.com/" />
<head>
<title>51前端</title>
<style type="text/css">
#txtTotal,#txtPrice{
  border-right-width:0px;
  margin-right:0px;
}
.money{
  border-left-width:0px;
  margin-left:-4px;
  width:18px;
}
</style>
<script type="text/javascript"> 
function checkInt(o){ 
  theV=isNaN(parseInt(o.value))?0:parseInt(o.value); 
  if(theV!=o.value){
 o.value=theV;
  } 
  txtTotal.value=txtAmount.value*txtPrice.value; 
} 
function checkP(o){ 
  theV=isNaN(parseFloat(o.value))?0:parseFloat(o.value); 
  theV=parseInt(theV*100)/100; 
  if(theV!=o.value){ 
    theV=(theV*100).toString(); 
    theV=theV.substring(0,theV.length-2)+"."+theV.substring(theV.length-2,theV.length) 
    o.value=theV; 
  } 
  txtTotal.value=txtAmount.value*txtPrice.value; 
} 
window.onload=function(){
  var txtAmount=document.getElementById("txtAmount");
  var txtPrice=document.getElementById("txtPrice");
  txtAmount.onkeyup=function(){
    checkInt(this)
  }
  txtAmount.onpaste=function(){
    checkInt(this);
  }
  txtAmount.oncut=function(){
    checkInt(this);
  }
  txtAmount.ondrop=function(){
    checkInt(this);
  }
  txtAmount.onchange=function(){
    checkInt(this);
  }
    
  txtPrice.onkeyup=function(){
    checkP(this)
  }
  txtPrice.onpaste=function(){
    checkP(this);
  }
  txtPrice.oncut=function(){
    checkP(this);
  }
  txtPrice.ondrop=function(){
    checkP(this);
  }
  txtPrice.onchange=function(){
    checkP(this);
  }
}
</script> 
</head> 
<body> 
数量: 
<input id="txtAmount" value="0" /> 
单价: 
<input id="txtPrice" value="0" /> 
<input class="money" value="¥" readonly> 
总价: 
<input id="txtTotal" value="0" readonly> 
<input class="money" value="¥" readonly>
</body> 
</html>

代码描述:JavaScript 输入单价数量 自动计算价格。JavaScript输入单价数量自动计算价格



662 883



用户评论
大牛,别默默的看了,快登录帮我点评一下吧!:)      登录 | 注册



×
×
51前端

注册

×
绑定手机

请绑定手机号,在继续操作

×
单次下载支付

应付金额:279

支付完成后,回到下载页面,在进行下载

官方QQ群
意见反馈
qq群

扫描上面二维码加微信群

官方QQ群

jQuery/js讨论群
群号:642649996
Css3+Html5讨论群
群号:322131262

加群请备注:从官网了解到