Skip to content

D030 Calculator

Starting with the following HTML, where two text boxes and a button have been created:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>DOM Tasks</title>
    <style>
      table tr td:first-child {
        width: 100px;
      }
    </style>
  </head>

  <body>
    <table>
      <tr>
        <td>1st number</td>
        <td><input class="num" type="text" value="0" /></td>
      </tr>
      <tr>
        <td>2nd number</td>
        <td><input class="num" type="text" value="0" /></td>
      </tr>
      <tr>
        <td colspan="2">
          <button id="button">Calculate</button>
        </td>
      </tr>
      <tr>
        <td>Sum</td>
        <td id="sum"></td>
      </tr>
    </table>

    <script src="app.js"></script>
  </body>
</html>

and the following JavaScript:

(function () {

// code

})();

You should create a “calculator” so that when the button is clicked, it adds together two numbers from the two text boxes and writes the result in the td#sum.

You might:

  • Find the two text boxes using querySelectorAll(".num") - but remember that this returns an array.
  • Retrieve the content of a text box using the value property.
Solution
(function() {
  // Button click handler
  document.getElementById('button').onclick = function() {
    // Get the two numbers
    let numbers = document.querySelectorAll('.num');
    let num1 = parseFloat(numbers[0].value);
    let num2 = parseFloat(numbers[1].value);

    // Calculate sum and display it
    document.getElementById('sum').textContent = num1 + num2;
  };

})();

Here is the solution using jQuery:

$(document).ready(function () {
  $("#button").click(function () {
    // Get the two input values
    let num1 = parseFloat($(".num").eq(0).val());
    let num2 = parseFloat($(".num").eq(1).val());

    // Calculate the sum and display it
    let sum = num1 + num2;
    $("#sum").text(sum);
  });
});

Run the provided HTML, and when you click the “Calculate” button, the sum of the two numbers entered will be displayed.