Creating a simple calculator

This is for a blog post: JavaScript Calculators & Code Creators

by David Roman-Halliday

HTML

<!doctype html>
<html lang="en">

  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Calculator Example</title>
    <!-- Note: for inline javascript, the code will go here -->
    <!-- Note: for jsfiddle.net, the code will go in the JavaScript frame -->
  </head>

  <body>
    <h1>Calculator Example</h1>

    <p>
      <label for="input_a">Input A: </label>
      <input name="input_a" type="number" value="100">
      <br/>
      <label for="input_b">Input B: </label>
      <input name="input_b" type="number" value="5">
    </p>

    <p>
      <input id="runButton" type="button" name="run" value="Run Calculations">
    </p>

    <p id="output">
      Output will be here
    </p>

  </body>

</html>

JavaScript

function my_calculation(x, y) {
  //This is our super clever maths operation.
  //Note: parseFloat() functions are required in some cases
  //      to make sure the interpreter sees two numbers,
  //      and doesn't concatenate two strings.
  return parseFloat(x) + parseFloat(y);
}

function calc() {
  //This example gets a list of all objects with a name
  //(in this case just one), and picks the first from the list.
  var value_a = document.getElementsByName("input_a")[0].value;
  var value_b = document.getElementsByName("input_b")[0].value;

  //This addreses the object by it's ID, which is cleaner.
  document.getElementById("output").innerText = my_calculation(value_a, value_b);
}

//This is required in jsfiddle.net as the classic onCLick
//event of the input button won't be icked up
var runButton = document.getElementById("runButton");
runButton.onclick = function() {
	calc();
}