0

我正在使用 javascript 为我的网络编程课程编写一个价格复选框页面,如果您选中这些框并单击小计,价格将被放入一个文本框中。我遇到的问题是当我用document.getElementById("subtotal").value = total它结束 if 语句时没有填充文本框。如果我插入一个alertordocument.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>
4

1 回答 1

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>
于 2013-10-20T15:10:40.823 回答