繁体   English   中英

价格显示和使用HTML输入复选框的价格更新

[英]Price display and Price Update with HTML Input Checkbox

我正在尝试构建一个Web应用程序,当用户选中一个框时,价格会更新。 示例:基本价格为$ 3,用户“复选框”变为$ 5,复选框2和3变为$ 10,依此类推。如何为此构建JavaScript代码? 这是下面的代码。

<label for="bathroomcleaning">Bathroom: </label>
<br>
<input type="checkbox"> Clean bowl and wipe down toilet cover, seat, under seat, base and behind the base.
<br>
<input type="checkbox"> Clean all mirrors.
<br>
<input type="checkbox"> Clean countertops and backsplashes.

我写了这个

function display() 
{ 
    var x = document.getElementById("myCheck").value; 
} 

但我还没有找到一种显示复选框的value属性的方法。 为了简化起见,我想知道是否可以首先显示复选框的值,然后想出如何添加它们的方法,但是我没有运气。

这是我用ID修改HTML的方法:

<label for="bathroomcleaning">Bathroom: </label>
<br>
<input type="checkbox" id="box-1"> Clean bowl and wipe down toilet cover, seat, under seat, base and behind the base.
<br>
<input type="checkbox" id="box-2"> Clean all mirrors.
<br>
<input type="checkbox" id="box-3"> Clean countertops and backsplashes.

然后,我做了一个新的<label>以显示价格:

<label for="bathroomprice" id="price">Price: </label>

然后,在其中添加了<script>标记和JavaScript脚本:

<script>

    function checkPrice() {
        var price = 3;
        if (document.getElementById("box-1").checked == true) {
            price = 5;
        }

        if (document.getElementById("box-2").checked == true && document.getElementById("box-3").checked == true) {
            price = 10;
        }

        document.getElementById("price").innerText = "Price: " + price;
    }

</script>

最后,我向所有<input>都添加了一个onclick事件,该事件会在您单击<input>时检查价格:

<label for="bathroomcleaning">Bathroom: </label>
<br>
<input type="checkbox" id="box-1" onclick="checkPrice()"> Clean bowl and wipe down toilet cover, seat, under seat, base and behind the base.
<br>
<input type="checkbox" id="box-2" onclick="checkPrice()"> Clean all mirrors.
<br>
<input type="checkbox" id="box-3" onclick="checkPrice()"> Clean countertops and backsplashes.

这是成品:

 <label for="bathroomcleaning">Bathroom: </label> <br> <input type="checkbox" id="box-1" onclick="checkPrice()"> Clean bowl and wipe down toilet cover, seat, under seat, base and behind the base. <br> <input type="checkbox" id="box-2" onclick="checkPrice()"> Clean all mirrors. <br> <input type="checkbox" id="box-3" onclick="checkPrice()"> Clean countertops and backsplashes. <br> <label for="bathroomprice" id="price">Price: </label> <script> function checkPrice() { var price = 3; if (document.getElementById("box-1").checked == true) { price = 5; } if (document.getElementById("box-2").checked == true && document.getElementById("box-3").checked == true) { price = 10; } document.getElementById("price").innerText = "Price: " + price; } </script> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM