你的位置:首页 > Java教程

[Java教程]js表单计算金额问题


<table width="600" border="1" align="center" style="text-align:center;">

  <tr>
    <td width="102"><input type="checkbox" id="all"/>全选</td>
    <td width="203">商品</td>
    <td width="119">单价</td>
    <td width="148">数量</td>
  </tr>
  <tr>
    <td><input type="checkbox" id="qianbi"/></td>
    <td>铅笔</td>
    <td>1.5元/支</td>
    <td><input type="text" id="qianbi_t" value="1" /></td>
  </tr>
  <tr>
    <td><input type="checkbox" id="yuanzhu" value="" /></td>
    <td>圆珠笔</td>
    <td>2.5元/支</td>
    <td><input type="text" id="yuanzhu_t" value="1" /></td>
  </tr>
  <tr>
    <td><input type="checkbox" id="gangbi" value="" /></td>
    <td>钢笔</td>
    <td>3元/支</td>
    <td><input type="text" id="gangbi_t" value="1" /></td>
  </tr>
  <tr>
    <td colspan="4">金额合计:<span id="m" style="color:#F00;"></span>元&nbsp;&nbsp;&nbsp;&nbsp;<button>提交订单</button></td>
  </tr>
</table>
<script type="text/javascript">
    var all=document.getElementById("all");
    var qianbi=document.getElementById("qianbi");
    var yuanzhubi=document.getElementById("yuanzhu");
    var gangbi=document.getElementById("gangbi");
    var qb_m=0,yzb_m=0,gb_m=0;
    all.onclick=function(){
        if(all.checked){
            qianbi.checked=true;
            yuanzhubi.checked=true;
            gangbi.checked=true;
        }
        else{
            qianbi.checked=false;
            yuanzhubi.checked=false;
            gangbi.checked=false;
        }
        sub();
    };
    qianbi.onclick=function(){sub()};
    yuanzhubi.onclick=function(){sub()};
    gangbi.onclick=function(){sub()};
    document.getElementById("qianbi_t").addEventListener("change",function(e){
        sub();
    });
    document.getElementById("yuanzhu_t").addEventListener("change",function(e){
        sub();
    });
    document.getElementById("gangbi_t").addEventListener("change",function(e){
        sub();
    });
    function sub(){
        if(qianbi.checked){
            qb_m=document.getElementById("qianbi_t").value*1.5
        }
        else{
            qb_m=0;
            all.checked=false;
        }
        if(yuanzhubi.checked){
            yzb_m=document.getElementById("yuanzhu_t").value*2.5
        }
        else{
            yzb_m=0;
            all.checked=false;
        }
        if(gangbi.checked){
            gb_m=document.getElementById("gangbi_t").value*3
        }
        else{
            gb_m=0;
            all.checked=false;
        }
        var sum=qb_m+yzb_m+gb_m;
        document.getElementById("m").innerHTML=sum;
    }
</script>