yakou tsuchimikado
yakou tsuchimikado

Reputation: 31

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?

Upvotes: 0

Views: 620

Answers (1)

Jack Bashford
Jack Bashford

Reputation: 44125

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">

Upvotes: 1

Related Questions