为什么我不能用document.getElementById(“ID”)结束我的if语句.value = var?

时间:2013-10-20 14:40:31

标签: javascript if-statement getelementbyid

我正在使用javascript为我的网络编程类编写一个价格复选框页面,如果你勾选方框并点击小计,价格会被放入文本框中。我遇到的问题是当我用document.getElementById("subtotal").value = total结束我的if语句时,它不会填充文本框。如果我插入alertdocument.write语句,则会填充它。知道我错过了什么吗?这是我的代码,其中包含警报(我不想要):

<!DOCTYPE html>

<head>
    <title> Price Checkbox </title>
    <meta charset = "utf-8" />
    <script>
        var total, a = 0;
    </script>
    <script type = "text/javascript">
        function subtotal1()
        {
            if (document.getElementById('apple').checked)
            {
                total = a + .59;
                a = total;
                document.getElementById("subtotal").value = total
                alert(total);
            }
            if(document.getElementById('orange').checked)
            {
                total = a + .49;
                a = total;
                document.getElementById("subtotal").value = total
                alert(total);
            }
            if(document.getElementById('banana').checked)
            {
                total = a + .39;
                a = total;
                document.getElementById("subtotal").value = total
                alert(total);
            }
        }
    </script>
 </head>
 <body>

     <form id = "myForm"  action = "">
         <p>
            <label> <input type = "checkbox"  id = "apple"/>
            apple $.59 </label>
            <br />
            <label> <input type = "checkbox"  id = "orange"/>
            orange $.49 </label>
            <br />
            <label> <input type = "checkbox"  id = "banana"/>
            banana $.39 </label>
         </p>

         <button onclick = "subtotal1()">Submit</button>
         <p></p>
         <input type="textbox" id="subtotal"/>
     </form>

</body>

1 个答案:

答案 0 :(得分:1)

我建议采用不同的方法。单击复选框时添加事件。通过这种方式,您还可以查看正在发生的事情,而不是在提交表单时将其保留。试试这段代码:

<body>

     <form id = "myForm"  action = "">
         <p>
            <label> <input type = "checkbox"  id = "apple"  onclick = "subtotal1();"/>
            apple $.59 </label>
            <br />
            <label> <input type = "checkbox"  id = "orange"  onclick = "subtotal1();"/>
            orange $.49 </label>
            <br />
            <label> <input type = "checkbox"  id = "banana"  onclick = "subtotal1();"/>
            banana $.39 </label>
         </p>

         <button>Submit</button>
         <p></p>
         <input type="textbox" id="subtotal"/>
     </form>

</body>