如何通过JavaScript不断访问HTML文本框

时间:2016-01-02 21:42:44

标签: javascript html forms

我在HTML中有一个非常简单的表单:

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

然后我有这个JavaScript:

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

我希望它能够解决,以便每当用户在文本框中键入任何内容时,它会执行所有JavaScript代码并输出steps,而无需任何提交按钮或类似内容。因此,如果用户要输入123,例如,当他们输入1时,它将在计算为1时输出steps,然后当他们输入2时,在计算为12时将输出steps ,当输入3时,当计算为123时,它将输出steps

3 个答案:

答案 0 :(得分:2)

使用onInput事件:

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

JavaScript的:

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

W3Schools documentation

示例:

&#13;
&#13;
function yourFunction() {
        var n = document.getElementById("form").value;
        document.getElementById("output").innerHTML = n;
}
&#13;
Input: <input id="form" type="text" name="Number" onInput="yourFunction();" />
<div id="output"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在input元素上注册onkeypress事件处理程序,让该处理程序进行计算。顺便说一句,你不需要表格容器。

答案 2 :(得分:0)

您需要捕获input事件,并在响应中运行代码

&#13;
&#13;
;(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);
    
  });

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

Number As Binary:
<output form="f" for="n" id="o"></output>
&#13;
&#13;
&#13;