JS实现填写数量自动计算显示数值
网站制作过程中,有这样的功能就是在填写框里填写数量之后,自动就会显示数值,这在我们的商城网站制作里常被用来制作计算商品的价格。
实现这样的功能,我们需要使用JS代码来实现,以下是实现填写数量自动计算显示数值的JS代码,可以通过修改里面的样式来达到各种效果。
<script>
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;
}
</script>
数量:
<input id=txtAmount value=0 onkeyup="checkInt(this);" onpaste="checkInt(this);" oncut="checkInt(this);" ondrop="checkInt(this);" onchange="checkInt(this);">
单价:
<input id=txtPrice value=0 onkeyup="checkP(this);" onpaste="checkP(this);" oncut="checkP(this);" ondrop="checkP(this);" onchange="checkP(this);" style="border-right-width:0px;margin-right:0px;">
<input style="border-left-width:0px;margin-left:-4px;width:18px" value="¥" readonly>
总价:
<input id=txtTotal value=0 style="border-right-width:0px;margin-right:0px;" readonly>
<input style="border-left-width:0px;margin-left:-4px;width:18px" value="¥" readonly>