Write a program in javascript to take two numbers as input from user and perform arithmetic operation based on the button choosen by user.

Write a program in javascript to take two numbers as input from the user and perform an arithmetic operation based on the button chosen by the user.


1. HTML

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Write a program in javascript to take two numbers as input</title>
</head>

<body>
  <div class="calculator">
    <h4>Calculator</h4>
    <input type="number" placeholder="0" id="one">
    <input type="number" placeholder="0" id="two">

    <p id="result"></p>

    <div class="btn-group">
      <button onclick="minus()">-</button>
      <button onclick="add()">+</button>
      <button onclick="divide()">/</button>
      <button onclick="modulo()">%</button>
      <button onclick="multiply()">X</button>
    </div>
  </div>

</body>

</html>


2. CSS

 <style>
    body {
      font-family: sans-serif;
      text-align: center;
    }

    label {
      font-weight: bold;
      line-height: 2.7;
    }


    .calculator {
      width: 20%;
      margin: auto;
      padding: 25px 10px;
      border-radius: 5px;
      background: #000;
      color: #fff;
    }

    input {
      width: 100px;
      padding: 10px;
      margin-bottom: 10px;
      border-radius: 5px;
      font-size: 15px;
      font-weight: bold;
      border-color: #00f;
    }

    button {
      border: none;
      padding: 10px 15px;
      font-weight: bold;
      font-size: 14px;
      color: #fff;
      background: blueviolet;
      border-radius: 4px;

    }

    #result {
      background: #514e4e99;
      padding: 15px 0px;
      margin: 20px 50px;
      border-radius: 5px;
    }
  </style>


3. JS

  <script>
    const result = document.getElementById("result");

    function getValueOne() {
      const numberOneValue = Number(document.getElementById("one").value);
      return numberOneValue;
    }

    function getValueTwo() {
      const numberTwoValue = Number(document.getElementById("two").value);
      return numberTwoValue;
    }

    function add() {
      result.innerHTML = getValueOne() + getValueTwo();
    }

    function minus() {
      result.innerHTML = getValueOne() - getValueTwo();
    }

    function modulo() {
      result.innerHTML = (getValueOne()) % (getValueTwo());
    }

    function multiply() {
      result.innerHTML = getValueOne() * getValueTwo();
    }

    function divide() {
      result.innerHTML = getValueOne() / getValueTwo();
    }
  </script>


4. Output


Codepen live


Reactions

Post a Comment

0 Comments