Toufic Batache Toufic Batache - 6 months ago 10
Javascript Question

How to make a special auto-subtractor?

I want to make with JS, a subtraction which auto-subtract the biggest number from the smallest one... How to do so ? Thanks

Answer

Using HTML5, if you listen for the oninput event of two <input type="number" /> fields, you can call Math.abs() on the difference between the two numbers, and it will update constantly.

Here's a small demo:

var input1 = document.getElementById("firstNum"),
    input2 = document.getElementById("secondNum"),
    output = document.getElementById("output");

input1.oninput = input2.oninput = function() {
  var num1 = parseInt(input1.value),
      num2 = parseInt(input2.value);
  output.innerHTML = Math.abs(num1 - num2);
};
Input 1: <input type="number" value="0" id="firstNum" /><br>
Input 2: <input type="number" value="0" id="secondNum" /><br>
Output: <span id="output">0</span>