<!DOCTYPE html> <html> <head> <title>Calculator</title> </head> <body> <h1>Calculator</h1> <form> <input type="text" id="num1" value="0"> <input type="text" id="num2" value="0"> <br> <input type="radio" name="operator" value="+" checked> + <input type="radio" name="operator" value="-"> - <input type="radio" name="operator" value="*"> * <input type="radio" name="operator" value="/"> / <br> <button type="button" onclick="calculate()">Calculate</button> <br> <h2>Result:</h2> <p id="result"></p> </form> <script> function calculator(num1, num2, operator) { if (operator === '+') { return num1 + num2; } else if (operator === '-') { return num1 - num2; } else if (operator === '*') { return num1 * num2; } else if (operator === '/') { return num1 / num2; } else { return 'Invalid operator'; } } function calculate() { const num1 = Number(document.getElementById('num1').value); const num2 = Number(document.getElementById('num2').value); const operator = document.querySelector('input[name="operator"]:checked').value; const result = calculator(num1, num2, operator); document.getElementById('result').textContent = result; } </script> </body> </html>
This HTML page includes a form with two text inputs for the numbers and four radio buttons for the operator. The form also includes a button to perform the calculation, and a paragraph element to display the result.
The calculator()
function performs the actual calculation, and the calculate()
function is called when the button is clicked. It gets the values of the inputs and the selected operator and then passes them to the calculator()
function. The result is then displayed in the result
paragraph element.