我是javascript的新手,我正在尝试制作一个能够立即计算所选产品总价的计算器。
计算器工作正常但是现在即使未经检查,复选框也会与其他产品一起计算。 我正在努力使它在未经检查时值为0,当它被检查时它是0.50。
这是我到目前为止所做的:
<head>
<style type="text/css">
.right{
margin-top: 10px;
width: 150px;
height: 45px;
background-color: #66CCFF;
}
p{
margin: 0;
padding: 0;
}
</style>
<script type="text/javascript">
<!--
function calculate() {
var A1 = document.getElementById('Amount1').value
var A2 = document.getElementById('Amount2').value
var A3 = document.getElementById('Amount3').value
var PStart = 0;
var P1 = A1*1.50;
var P2 = A2*1.00;
var P3 = A3*1.00;
var PTotal = P1+P2+P3;
var Insert = document.getElementById("TotalPrice");
TotalPrice.innerHTML= PTotal;
}
-->
</script>
</head>
<body onload="calculate()">
<form>
<fieldset>
<legend>Price</legend>
<div class="FormRow">
<label for="Amount2">Console $1,50</label>
<input type="text" min=0 id="Amount1" name="Amount1" oninput="calculate()" />
</div>
<div class="FormRow">
<label for="Amount2">Controller $1,00</label>
<input type="text" min=0 id="Amount2" name="Amount2" oninput="calculate()" />
</div>
<div class="FormRow">
<label for="Amount3">Batteries? $0,50</label>
<input type="checkbox" value="0.50" id="Amount3" name="Amount3" onchange="calculate()"/>
</div>
<div class="right" >
<p><b>Total price:</b></p>
<p id="TotalPrice">
</p>
</div>
</fieldset>
</form>
</body>
答案 0 :(得分:0)
您可以使用document.getElementById('Amount1').checked
验证是否选中了复选框。所以你的代码看起来像
var A1 = document.getElementById('Amount1').checked ?
parseFloat(document.getElementById('Amount1').value) :
0;
var A2 = document.getElementById('Amount1').checked ?
parseFloat(document.getElementById('Amount1').value) :
0;
var Total = A1 + A2;
答案 1 :(得分:0)
试试这个:
var A1 = document.getElementById('Amount1').value
var A2 = document.getElementById('Amount2').value
var A3 = document.getElementById('Amount3').checked ?
document.getElementById('Amount3').value : 0;