Advertisement
richarduie

simpleCalculator.html

Mar 31st, 2013
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 1.61 KB | None | 0 0
  1. <html>
  2.  
  3. <head>
  4.     <script type="text/JavaScript">
  5.         function get(eid) {return document.getElementById(eid);};
  6.         function calculate(op){
  7.             var a = parseFloat(get('a').value);
  8.             var b = parseFloat(get('b').value);
  9.             if (isNaN(a) || isNaN(b)) {
  10.                 alert('both inputs must be numbers');
  11.                 return;
  12.             }
  13.             var answer;
  14.             switch (op) {
  15.                 case 'add': {
  16.                     answer = a + ' + ' + b + ' = ' + (a + b);
  17.                     break;
  18.                 }
  19.                 case 'subtract': {
  20.                     answer =  a + ' - ' + b + ' = ' + (a - b);
  21.                     break;
  22.                 }
  23.                 case 'multiply': {
  24.                     answer =  a + ' * ' + b + ' = ' + (a * b);
  25.                     break;
  26.                 }
  27.                 case 'divide': {
  28.                     if (0 == b) {
  29.                         alert('illegal value - cannot divide by 0');
  30.                         return;
  31.                     }
  32.                     answer =  a + ' / ' + b + ' = ' + (a / b);
  33.                     break;
  34.                 }
  35.             }
  36.             get('resultAsTextBox').value = answer;
  37.         }
  38.     </script>
  39. </head>
  40.  
  41. <body>
  42.     <form>
  43.         <p>
  44.             Instructions:<br />
  45.             Type two numbers and click a button.<br />
  46.             The answer will then appear below.<br /><br />
  47.             Input values:<br/ >
  48.             First number to include: = <input id="a" type="text" /><br />
  49.             Second number to include: = <input id="b" type="text" /><br /><br />
  50.             <input type="button" value="add" onclick="calculate(this.value)" />
  51.             <input type="button" value="subtract" onclick="calculate(this.value )" />
  52.             <input type="button" value="multiply" onclick="calculate(this.value)" />
  53.             <input type="button" value="divide" onclick="calculate(this.value)" /><br />
  54.             Output value:<br />
  55.             Result= <input type="text" id="resultAsTextBox" size="50" disabled="disabled" />
  56.         <p>
  57.     </form>
  58. </body>
  59.  
  60. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement