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

时间:2018-10-08 23:09:35

标签: javascript html

我正在尝试构建一个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属性的方法。为了简化起见,我想知道是否可以首先显示复选框的值,然后想出如何添加它们的方法,但是我没有运气。

1 个答案:

答案 0 :(得分:0)

这是我用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>

最后,我向所有onclick都添加了<input>事件,该事件在您每次点击<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>