settingsAccountsettings
Menusettings

Q: Subtraction Task in HTML with DOM and JavaScript

+2 votes

A HTML page holds two text fields "firstNumber" and "secondNumber". Write a JS function to subtract the values from these text fields and display the result in a div named "result".

HTML and JavaScript Code - You are given the following HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Subtraction</title>
</head>
<body>
<div id="wrapper">
    <input type="text" id="firstNumber" value="13.33" disabled>
    <input type="text" id="secondNumber" value="22.18" disabled>

    <div id="result"></div>
</div>
<script src="subtract.js"></script>
<script>
    window.onload = function () {
        subtract();
    }
</script>
</body>
</html>

Implement the above to provide the following functionality:

  • Your function should take the values of "firstNumber" and "secondNumber", convert them to numbers, subtract the second number from the first and then write the result in the <div> with id="result"
  • Your function should be able to work with any 2 numbers in the inputs, not only the ones given in the example. It may hold other functions in its body.

Examples:

subtraction javascript task

asked in JavaScript category by user ak47seo

1 Answer

+1 vote

Here is my solution - with HTML and the JavaScript code inside:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Subtraction</title>
</head>
<body>
<div id="wrapper">
    <input type="text" id="firstNumber" value="13.33" disabled>
    <input type="text" id="secondNumber" value="22.18" disabled>

    <div id="result"></div>
</div>
<script src="subtract.js"></script>
<script>
    window.onload = function () {
        subtract();
    }
</script>

<script>
    function subtract() {
        let num1 = Number(document.getElementById("firstNumber").value);
        let num2 = Number(document.getElementById("secondNumber").value);
        let result = num1 - num2;
        document.getElementById("result").textContent = result;
    }
</script>
</body>
</html>

 

answered by user andrew
...