简体   繁体   中英

Change event event not fired

what happened when a change event fired? which is the conditions that fired the change event?

 let i = document.querySelector('input') i.addEventListener('change', e => console.log(e)) i.dispatchEvent(new Event('change'))//listener will be triggered but radio element will not be selected i.checked = true // radio element will be selected but listener will not be triggered i.click() //radio element will be selected and listener will be triggered 
 <input name="test" type="radio" value="1"> <input name="test" type="radio" value="2"> 
So when user selecting radio nomally what did browser do? set the checked property to true and dispatch a change event?

A change event is fired when (particularly with input elements) the value is changed - so if you read the value, then read it after a change call, the two values would be different.

 let i = document.querySelector('input') i.addEventListener('change', e => console.log(e)) i.checked = true //Nothing happened i.click() //event object is output 
 <input name="test" type="radio" value="1"> <input name="test" type="radio" value="2"> 

Your above code isn't firing the event straightaway because you're clicking the input - and even so, because it's already selected, the value won't change, so nothing will happen. If you remove the checked = true part, it will fire, because the value is going from unchecked (not filled) to checked (filled) when you click the element:

 let i = document.querySelector('input') i.addEventListener('change', e => console.log(e)) i.click() //event object is output 
 <input name="test" type="radio" value="1"> <input name="test" type="radio" value="2"> 

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