Simple Calculator

Learn how to interact with buttons on text tags

by akmiecik

HTML

<div class="calc">
      <input class="number_input" type="text" name="x"  value="2531" onchange="calculate()" >
        <select name="choose_operator" id="choose_operator" onchange="calculate()">
          <option name="operator" value="+"> + </option>
          <option name="operator" value="-"> - </option>
          <option name="operator" value="*"> * </option>
          <option name="operator" value="/"> / </option>
        </select>
      <input class="number_input" type="text" name="y"  value="20" onchange="calculate()"> = 
      <input class="number_input" type="text" disabled="disabled" name="total" value="" >
    </div>

CSS

.number_input{
  width: 100px;
  height: 50px;
  text-align: center;
}
       
.calc{
  margin-top: 25px;
}

JavaScript

window.calculate = function (){
      var x = document.getElementsByName('x')[0].value;
      var y = document.getElementsByName('y')[0].value;
      var total;
      var selected_index = document.getElementById('choose_operator').selectedIndex;
      var selected_operator = document.getElementById('choose_operator').options[selected_index].value;
      // console.log('You have selected ' + selected_operator)
      
      if (selected_operator == '+'){
        total = parseFloat(x) + parseFloat(y);
      }
      else if (selected_operator == '-'){
        total = parseFloat(x) - parseFloat(y);
      }
      else if(selected_operator == '*'){
       total = parseFloat(x) * parseFloat(y); 
      }
      else{
        total = parseFloat(x) / parseFloat(y)
      }
      // Passing the result to the text box
      document.getElementsByName('total')[0].value = total;
    }
    calculate()