Best way to track onchange as-you-type in input type=“text”?

后端 未结 16 1348
天命终不由人
天命终不由人 2020-11-22 08:42

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

Is there a way to

16条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 08:59

    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 
    

提交回复
热议问题