[javascript] Best way to track onchange as-you-type in input type="text"?

In my experience, input type="text" onchange event usually occurs only after you leave (blur) the control.

Is there a way to force browser to trigger onchange every time textfield content changes? If not, what is the most elegant way to track this “manually”?

Using onkey* events is not reliable, since you can right-click the field and choose Paste, and this will change the field without any keyboard input.

Is setTimeout the only way?.. Ugly :-)

This question is related to javascript html forms

The answer is


To track each try this example and before that completely reduce cursor blink rate to zero.

_x000D_
_x000D_
<body>_x000D_
//try onkeydown,onkeyup,onkeypress_x000D_
<input type="text" onkeypress="myFunction(this.value)">_x000D_
<span> </span>_x000D_
<script>_x000D_
function myFunction(val) {_x000D_
//alert(val);_x000D_
var mySpan = document.getElementsByTagName("span")[0].innerHTML;_x000D_
mySpan += val+"<br>";_x000D_
document.getElementsByTagName("span")[0].innerHTML = mySpan;_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

onblur : event generates on exit

onchange : event generates on exit if any changes made in inputtext

onkeydown: event generates on any key press (for key holding long times also)

onkeyup : event generates on any key release

onkeypress: same as onkeydown (or onkeyup) but won't react for ctrl,backsace,alt other


onkeyup happens after you type for example I press t when I lift the finger the action happens but on keydown the action happens before I digit the character t

Hope this is helpful for someone.

So onkeyup is better for when you want to send what you just typed now.


"input" worked for me.

var searchBar  = document.getElementById("searchBar");
searchBar.addEventListener("input", PredictSearch, false);

Javascript is unpredictable and funny here.

  • onchange occurs only when you blur the textbox
  • onkeyup & onkeypress doesn't always occur on text change
  • onkeydown occurs on text change (but cannot track cut & paste with mouse click)
  • onpaste & oncut occurs with keypress and even with the mouse right click.

So, to track the change in textbox, we need onkeydown, oncut and onpaste. In the callback of these event, if you check the value of the textbox then you don't get the updated value as the value is changed after the callback. So a solution for this is to set a timeout function with a timeout of 50 mili-seconds (or may be less) to track the change.

This is a dirty hack but this is the only way, as I researched.

Here is an example. http://jsfiddle.net/2BfGC/12/


Below code works fine for me with Jquery 1.8.3

HTML : <input type="text" id="myId" />

Javascript/JQuery:

$("#myId").on('change keydown paste input', function(){
      doSomething();
});

there is a quite near solution (do not fix all Paste ways) but most of them:

It works for inputs as well as for textareas:

<input type="text" ... >
<textarea ... >...</textarea>

Do like this:

<input type="text" ... onkeyup="JavaScript: ControlChanges()" onmouseup="JavaScript: ControlChanges()" >
<textarea ... onkeyup="JavaScript: ControlChanges()" onmouseup="JavaScript: ControlChanges()" >...</textarea>

As i said, not all ways to Paste fire an event on all browsers... worst some do not fire any event at all, but Timers are horrible to be used for such.

But most of Paste ways are done with keyboard and/or mouse, so normally an onkeyup or onmouseup are fired after a paste, also onkeyup is fired when typing on keyboard.

Ensure yor check code does not take much time... otherwise user get a poor impresion.

Yes, the trick is to fire on key and on mouse... but beware both can be fired, so take in mind such!!!


You could use the keydown, keyup and keypress events as well.


I think in 2018 it's better to use the input event.

-

As the WHATWG Spec describes (https://html.spec.whatwg.org/multipage/indices.html#event-input-input):

Fired at controls when the user changes the value (see also the change event)

-

Here's an example of how to use it:

<input type="text" oninput="handleValueChange()">

Method 1: Add an event listener for input:

element.addEventListener("input", myFunction);

 

Method 2: Define the oninput property with JavaScript:

element.oninput = function()
{
    myFunction();
};

 

Method 3: Define the oninput property with HTML:

<input type="text" oninput="myFunction();">

2018 here, this is what I do:

$(inputs).on('change keydown paste input propertychange click keyup blur',handler);

If you can point out flaws in this approach, I would be grateful.


Robert Siemer addEventListener is not supported in IE8 .

"Older versions of IE supported an equivalent, proprietary EventTarget.attachEvent() method." https://developer.mozilla.org/it/docs/Web/API/Element/addEventListener


Use oninput instead of onchange.

index.html

<html>
  <head>
    <title>title here</title>
    <script src="index.js"></script>
  </head>
  <body>
    <input oninput="onclickhandler(this)"></input>
  </body>
</html>

script.js

function onclickhandler(e) {
  console.log(e.value);
}


Please, judge next approach using JQuery:

HTML:

<input type="text" id="inputId" />

Javascript(JQuery):

$("#inputId").keyup(function(){
        $("#inputId").blur();
        $("#inputId").focus();
});

$("#inputId").change(function(){
        //do whatever you need to do on actual change of the value of the input field
});

If you use ONLY Internet Explorer, you can use this:

<input type="text" id="myID" onpropertychange="TextChange(this)" />

<script type="text/javascript">
    function TextChange(tBox) {
        if(event.propertyName=='value') {
            //your code here
        }
    }
</script>

Hope that helps.


These days listen for oninput. It feels like onchange without the need to lose focus on the element. It is HTML5.

It’s supported by everyone (even mobile), except IE8 and below. For IE add onpropertychange. I use it like this:

_x000D_
_x000D_
const source = document.getElementById('source');_x000D_
const result = document.getElementById('result');_x000D_
_x000D_
const inputHandler = function(e) {_x000D_
  result.innerHTML = e.target.value;_x000D_
}_x000D_
_x000D_
source.addEventListener('input', inputHandler);_x000D_
source.addEventListener('propertychange', inputHandler); // for IE8_x000D_
// Firefox/Edge18-/IE9+ don’t fire on <select><option>_x000D_
// source.addEventListener('change', inputHandler); 
_x000D_
<input id="source">_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_


I had a similar requirement (twitter style text field). Used onkeyup and onchange. onchange actually takes care of mouse paste operations during lost focus from the field.

[Update] In HTML5 or later, use oninput to get real time character modification updates, as explained in other answers above.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"