简体   繁体   中英

keydown event : how use preventdefault without break fire of change event

I need to intercept and replace chars in input text, so have the following code for keydown event handler for an input text :

 let my_input = document.querySelector("#my_input"); my_input.addEventListener('keydown', (e) => { e.target.value = 'toto'; e.preventDefault(); var event = new Event('input', { 'bubbles': true, 'cancelable': true }); e.target.dispatchEvent(event); }); my_input.addEventListener('change', (e) => { //never fired even you focus out the input text console.log("changes are coming"); }); 
 <input type="text" id="my_input" pattern="^\\d+((\\.|\\,)(\\d{1,2})?)?" /> 

What seems odd to me is that when focusout event is fired, then change event is never fired.

Do you understand what happends and how to make it work normally?

Use the onblur event. e.preventDefault() is causing your problem by changing the normal behavior of the input .

 <input type="text" id="my_input" onblur="myFunction()"/> <script> let my_input = document.querySelector("#my_input"); var changed = false; my_input.addEventListener('keydown', (e) => { e.target.value = 'toto'; e.preventDefault(); changed = true; var event = new Event('input', { 'bubbles': true, 'cancelable': true }); e.target.dispatchEvent(event); }); function myFunction(){ if(changed){ console.log("changes are coming"); changed = false; } } </script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM