2015-05-14 47 views
3

以下功能似乎沒有工作..單選按鈕選中的JavaScript - 沒有jQuery的

function myCalculator() { 

    var operator = document.getElementsByName("operator"); 
    var output = document.getElementById("output"); 
    var firstDig = parseInt(document.getElementById("firstDig").value); 
    var secondDig = parseInt(document.getElementById("secondDig").value); 

    for (var i=0; i<operator.length; i++){ 

     var currentOperator = operator[i].id; 

     if(currentOperator.checked == "Add"){ 
      var add = firstDig + secondDig; 
       output = add; 
     }; 


    }; 

     } 

莫名其妙的「如果」參數,返回false,但我得到了與該屬性的元素檢查...即時決策一個簡單的計算器...以下是HTML ...

<fieldset> 

    <label>Enter Number:</label> 
    <input type="text" id="firstDig" /> 
    <input type="text" id="secondDig" /> 
     <br/> <br/> 
    <label>Select Operator:</label> 
    <br/><br /> 

    <input type="radio" id="Add" name="operator" checked="checked" /> 
     <label for = "Add">Add</label> 

    <input type="radio" id="Subt" name="operator" /> 
     <label for = "Subt">Subtract</label> 

    <input type="radio" id="Divi" name="operator" /> 
     <label for = "Divi">Divide</label> 

    <input type="radio" id="Multi" name="operator" /> 
     <label for = "Multi">Multiply</label> 

</fieldset> 


<fieldset> 
    <p>RESULT</p> 
    <input type="text" id="output" /> 
    <button type="button" onclick="myCalculator()">Calculate</button> 
</fieldset> 

我還在學習JavaScript所以我不會的,在目前jQuery中inetrested基礎......所有的答案都感激.. 。比ks

回答

3

checked屬性將具有true/false值,因此您需要獲取已檢查的收音機,然後查看其ID是否爲Add(您沒有將值分配給無線電元素,而是具有ID)。

以同樣的方式output是輸入元素,所以你需要指定它的價值

function myCalculator() { 

    var operator = document.getElementsByName("operator"); 
    var output = document.getElementById("output"); 
    var firstDig = parseInt(document.getElementById("firstDig").value); 
    var secondDig = parseInt(document.getElementById("secondDig").value); 

    for (var i = 0; i < operator.length; i++) { 

     var currentOperator = operator[i], 
      result = ''; 

     if (currentOperator.checked) { 
      if (currentOperator.id == "Add") { 
       result = firstDig + secondDig; 
      } else if (currentOperator.id == "Subt") { 
       result = firstDig - secondDig; 
      } 
      output.value = result; 
     }; 


    }; 

} 
+0

@DhavalMarthak是你的權利 –

+0

''currentOperator本身是抱着'id'所以shud be'currentOperator ==「添加」 – Zee

+0

@ Sourabh-是剛剛更正 –

1
if(currentOperator.checked == "Add"){.. 

是錯誤的。它只能有2個值truefalse。您可以檢查它想:

if(currentOperator == "Add" && operator[i].checked){.. 

而且output = add;

shud是

output.value = add; 
0

變化 輸出=增加; 至 output.value = add;

0
for (var i=0; i<operand.length; i++){ 
var currentOperand = operand[i]; 
if (currentOperand.checked && currentOperand.id == "Add") { 
var add = firstDig + secondDig; 
output.value = add; 
}else if (currentOperand,checked && currentOperand.id == "Subt"){ 
var subt = firstDig - secondDig; 
output.value = subt; 
}; 

我已延長我的,如果有else語句,如果它停止工作......以爲我擁有