复选框的空值 - 切换语句

时间:2014-06-11 05:23:35

标签: javascript dom

我的基本表单包含输入文本框和复选框。该示例目前显示两个项目。我正在尝试使用开关盒来确定检查的内容,然后根据数量和用户选择计算总数。我在mufin1.checked == true的开关案例中收到错误。如何获得适当的返回值? JSFIDDLE

JS

  function charge(){
      var q_muffin1 = document.getElementById('muffin_quantity1');
      var muffin1 = document.getElementById('muffin1');
      var q_muffin2 = document.getElementById('muffin_quantity2');
      var muffin2 = document.getElementById('muffin2');
      var charge;
      var form = document.getElementById("muffinOrder");
      var checkbox = form.getElementsByTagName("checkbox");

      switch (checkbox.checked) {
          case (mufin1.checked ==  true):
          charge += q_muffin1 * muffin1;
          break;
          case (mufin2.checked ==  true):
          charge += q_muffin2 * muffin2;
          break;
        default:
          window.alert("Sorry, we are out of");
      }
      window.alert("Your total is: $" + charge);
      return false;
 }

HTML

<form action="" id="muffinOrder" onsubmit="return charge()">
Quantity: <input type="text" name="muffin_quantity1" id="muffin_quantity1"><input type="checkbox" name="muffin1" id="muffin1" value=".59">Blueberry Muffin .59&cent;<br />
Quantity: <input type="text" name="muffin_quantity2" id="muffin_quantity2"><input type="checkbox" name="muffin2" id="muffin2" value=".69">Banana Nutted Muffin .90&cent;<br />
<input type="submit" value="Submit" >
 </form>

2 个答案:

答案 0 :(得分:3)

假设您不想处理选中两个复选框的情况,您可以这样写:

switch (true) {
      case (mufin1.checked):
      charge += q_muffin1 * muffin1;
      break;
      case (mufin2.checked):
      charge += q_muffin2 * muffin2;
      break;
    default:
      window.alert("Sorry, we are out of");
  }

但是如果没有那些变量xxx1和xx2,你的整个代码可能会更清晰。我不确定整个目标,但这可能是这样的:

var charge = 0;
[1,2].forEach(function(id){
   var muffin = document.getElementById('muffin'+id);
   var q_muffin = document.getElementById('muffin_quantity'+id).value;
   if (muffin.checked) charge += q_muffin;
});
window.alert("Your total is: $" + charge);

答案 1 :(得分:0)

string str=Convert.toString(checkbox.checked);//int return With Null Value in ""
  switch (str.toUpper()) {
          case "TRUE":
          charge += q_muffin1 * muffin1;
          break;
          case "FALSE":
          charge += q_muffin2 * muffin2;
          break;
        default:
          window.alert("Sorry, we are out of");
      }
      window.alert("Your total is: $" + charge);

检查此