Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'd suggest the following (explanations commented in the code itself):</p> <pre><code>function calc() { /* finds out whether the browser uses textContent (Webkit, Opera, Mozilla...) or innerText (Microsoft) to set the text of an element/node */ var textType = Node.textContent ? 'textContent' : 'innerText', /* uses parseFloat to create numbers (where possible) from the entered value if parseFloat fails to find a number (it's empty or nonsensical) then a 0 is used instead (to prevent NaN being the output). */ num1 = parseFloat(document.getElementById('num1').value) || 0, num2 = parseFloat(document.getElementById('num2').value) || 0, // retrieves the result element result = document.getElementById('result'); // switch is used to avoid lots of 'if'/'else if' statements, // .replace() is used to remove leading, and trailing, whitespace // could use .trim() instead, but that'd need a shim for (older?) IE switch (document.getElementById('op').value.replace(/\s/g,'')){ // if the entered value is: // a '+' then we set the result element's text to the sum case '+': result[textType] = num1 + num2; break; // and so on... case '-': result[textType] = num1 - num2; break; case '*': result[textType] = num1 * num2; break; case '/': result[textType] = num1 / num2; break; // because people are going to try, give a default message if a non-math // operand is used default: result[textType] = 'Seriously? You wanted to try math with that operand? Now stop being silly.' break; } } </code></pre> <p><a href="http://jsfiddle.net/davidThomas/wxhU9/4/" rel="nofollow">JS Fiddle demo</a>.</p> <p>References:</p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseFloat" rel="nofollow"><code>parseFloat()</code></a>.</li> <li><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/switch" rel="nofollow"><code>switch () {...}</code></a>.</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload