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:
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
valueproperty.
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:
Run the provided HTML, and when you click the “Calculate” button, the sum of the two numbers entered will be displayed.