代码描述:JavaScript 输入单价数量 自动计算价格。JavaScript输入单价数量自动计算价格
在大多数商城都有这样的功能,当输入商品数量和商品的单价,就会自动计算出来商品的总价格,非常的人性化,省却了用户不少时间,下面是一段类似的代码实例,希望能够给大家带来一定的帮助。 代码实例如下:
<!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>
请绑定手机号,在继续操作
注意:只有绑定手机以后,才可使用网站全部功能