0

I have a very simple form in HTML:

<form>
  Number: <input id="form" type="text" name="Number"/>
</form>

Then I have this JavaScript:

var n = document.getElementById("form").value;
//calculations with n
//later, it outputs another variable (steps) that comes from that value of n

I want it to work out so that whenever the user types anything into the textbox, it does all of the JavaScript code and outputs the steps without having any submit button or anything like that. So if the user is going to type 123, for example, when they type 1, it will output steps when calculated for 1, then when they type the 2, it will output steps when calculated for 12, then when the type the 3, it will output steps when calculated for 123.

Ahmad Alfy
  • 13,107
  • 6
  • 65
  • 99
CPC
  • 163
  • 5
  • 17

3 Answers3

2

Use onInput event:

<input id="form" type="text" onInput="yourFunction();" />

JavaScript:

function yourFunction() {
    var n = document.getElementById("form").value;
}

W3Schools documentation


Example:

function yourFunction() {
        var n = document.getElementById("form").value;
        document.getElementById("output").innerHTML = n;
}
Input: <input id="form" type="text" name="Number" onInput="yourFunction();" />
<div id="output"></div>
Thomas Orlita
  • 1,554
  • 14
  • 28
0

Register an onkeypress event handler on the input element and let that handler do the calculation. Btw you don't need the form container.

Darko Maksimovic
  • 1,155
  • 12
  • 14
0

You need to trap the input event, and run your code in response

;(function(){
  "use strict";
  
  //  make sure the DOM is available
  document.addEventListener('DOMContentLoaded',function(){

    //  function that does the work
    var calculateResult = function(event){
      o.value = n.valueAsNumber.toString(2);
    };    
    
    //  select the DOM elements
    var n = document.getElementById('n');
    var o = document.getElementById('o');
    
    //  attach your function to the input event
    n.addEventListener('input',calculateResult);
    
  });

})();
<form id="f">
  Number: <input id="n" type="number" name="n"/>
</form>

Number As Binary:
<output form="f" for="n" id="o"></output>
code_monk
  • 9,451
  • 2
  • 42
  • 41