2014-02-15 82 views
0

HTML與下拉

 function calculate() { 
      try 
      { 
      var value1 = parseInt(validate(document.getElementById("value1").value.trim())); 
      var value2 = parseInt(validate(document.getElementById("value2").value.trim())); 
      document.getElementById("result").value = operate(value1, value2); 
      } 
      catch (err) { 
       alert("There was a problem: " + err.messaqge); 
      } 
     } 
      catch (err) { 
       alert("There was a problem: " + err.messaqge); 
      } 
     } 

     function operate(value1, value2) { 
      if (operator == addition) { 
       return value1 + value2; 
      } else if (operator == subtraction) { 
       return value1 - value2; 
      } else if (operator == division) { 
       return value1/value2; 
      } else if (operator == multiplication) { 
       return value1 * value2; 
      } 

      function validate(value) { 
       if (value == null || value == "") { 
        alert("Required Field"); 
        return 0; 
       } else if (isNaN(value)) { 
        alert("Must be a Number Field"); 
        return 0; 
       } else return value; 
      } 
     } 
    </script> 
    <title>Title Bar</title> 
    </head> 
    <body> 
     <h2>Calculator</h2> 
     <table border="1"> 
      <tr> 
      <td>Value 1: </td> 
      <td><input type="text" id="value1" name="value1"/></td> 
      </tr> 
      <tr> 
      <td>Value 2: </td> 
      <td><input type="text" id="value2" name="value2" /></td> 
      </tr> 
      <tr> 
      <td>Operator: </td> 
      <td><select id="operator"> 
      <option value="Add">+</option> 
      <option value="Subtract">-</option> 
      <option value="Multiply">*</option> 
      <option value="Divide">/</option> 
      </select></td> 
      </tr> 
      <tr> 
      <td>Result: </td> 
      <td><input type="text" id="result" name="result" /></td> 
      </tr> 
     </table> 
     <input type="submit" id="btn_sub" name="btn_sub" value="Submit" onclick="calculate()" /> 
     <input type="reset" id="btn_res" name="btn_res" value="Reset" /> 
    </body> 
</html> 

這種/ JavaScript的計算器是一個非常基本的計算器程序。我只是補充它,它正在工作,但我正在嘗試添加下拉菜單,以便我可以執行不同的操作,並且我無法使其工作。它只能是計算函數中的操作函數或第三行,因爲當它只是用於加法時,其他所有操作都在工作。

回答

1

你可以得到的降值下使用:

var operator = document.getElementById('operator').value; 

入住這個例子中,我採取了運營商值,然後把它傳遞給operate

http://jsfiddle.net/wE77s/2/

+0

完美,三江源 – user3312259

+0

不用客氣,如果您認爲這對您有幫助,您應該將問題設置爲回答。 – rolnn