选中复选框时功能触发,未选中则清除

时间:2018-09-20 14:35:04

标签: javascript checkbox

这是一个简单的计算,它在选中复选框时运行:

function calculate() {
   var guests = document.getElementById("guests").value;
   var drinkRate = 2;
   var drinkCost = drinkRate * guests;

   //output
   document.getElementById("drinkPrice").value = '$' + 
   parseFloat(drinkCost).toFixed(2);
};
Number of guests: 
<input type="number" name="guests" id="guests" value="4"><br>
Drinks<input type="checkbox" name="drinks" id="A" onchange="calculate()"><output id="drinkPrice"></output><br>

如果未选中此复选框,如何清除(或隐藏)计算?

谢谢

4 个答案:

答案 0 :(得分:4)

您可以使用复选框的checked属性来确定该复选框处于选中状态还是未选中状态。该示例的代码为:

function calculate() {

 if (document.getElementById("A").checked) {
  var guests = document.getElementById("guests").value;
  var drinkRate = 2;
  var drinkCost = drinkRate * guests;

  //output
  document.getElementById("drinkPrice").value = '$' +
   parseFloat(drinkCost).toFixed(2);
 } else {
  document.getElementById("drinkPrice").value = "";
 }

};
Number of guests: 
<input type="number" name="guests" id="guests" value="4">
<br>
Drinks: 
<input type="checkbox" name="drinks" id="A" onchange="calculate()">

<output id="drinkPrice"></output><br>

答案 1 :(得分:1)

出于兼容性原因,我强烈建议您不要使用onchange事件,而应使用onclick,最好由@ T.J解释。 this question

上的人群

只需将复选框标签内的onchange="calculate(this)"更改为:

<input type='checkbox' onclick='calculate(this);'>

答案 2 :(得分:0)

您必须检查复选框检查值是否为true。 试试这个。

function calculate() {
 if (!document.getElementById("A").checked) {
  document.getElementById("drinkPrice").value = "";
 } else {
  var guests = document.getElementById("guests").value;
  var drinkRate = 2;
  var drinkCost = drinkRate * guests;
  document.getElementById("drinkPrice").value = '$' + parseFloat(drinkCost).toFixed(2);
 }

};
     
 Number of guests: 
<input type="number" name="guests" id="guests" value="4"><br>
Drinks<input type="checkbox" name="drinks" id="A" onchange="calculate()"><output id="drinkPrice"></output><br>

答案 3 :(得分:0)

检查复选框的当前状态,如果状态为false,则重置该值。

function calculate() {
   var guests = document.getElementById("guests").value;
   var drinkRate = 2;
   var drinkCost = drinkRate * guests;

   //output
   document.getElementById("drinkPrice").value = '$' + 
   parseFloat(drinkCost).toFixed(2);

   if(!document.getElementById('A').checked) {
        document.getElementById("drinkPrice").value = ""
   }
};
Number of guests: 
<input type="number" name="guests" id="guests" value="4"><br>
Drinks<input type="checkbox" name="drinks" id="A" onchange="calculate()"><output id="drinkPrice"></output><br>