Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :-)

like image 994
Ilya Birman Avatar asked Feb 22 '09 13:02

Ilya Birman


2 Answers

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:

const source = document.getElementById('source');  const result = document.getElementById('result');    const inputHandler = function(e) {    result.innerHTML = e.target.value;  }    source.addEventListener('input', inputHandler);  source.addEventListener('propertychange', inputHandler); // for IE8  // Firefox/Edge18-/IE9+ don’t fire on <select><option>  // source.addEventListener('change', inputHandler); 
<input id="source">  <div id="result"></div>
like image 58
Robert Siemer Avatar answered Sep 30 '22 19:09

Robert Siemer


Update:

See Another answer (2015).


Original 2009 Answer:

So, you want the onchange event to fire on keydown, blur, and paste? That's magic.

If you want to track changes as they type, use "onkeydown". If you need to trap paste operations with the mouse, use "onpaste" (IE, FF3) and "oninput" (FF, Opera, Chrome, Safari1).

1Broken for <textarea> on Safari. Use textInput instead

like image 34
Crescent Fresh Avatar answered Sep 30 '22 20:09

Crescent Fresh