Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Web Technology by (40.7k points)

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

1 Answer

0 votes
by (20.3k points)

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

It'll be supported by everyone (even mobile), except IE8 and below. For IE add onpropertychange. You can use it like this:

const $source = document.querySelector('#source');

const $result = document.querySelector('#result');

const typeHandler = function(e) {

  $result.innerHTML = e.target.value;

}

$source.addEventListener('input', typeHandler) // register for oninput

$source.addEventListener('propertychange', typeHandler) // for IE8

// $source.addEventListener('change', typeHandler) // fallback for Firefox for <select><option>, for <input> oninput is enough

<input id="source" />

<div id="result"></div>

Browse Categories

...