Is it possible to have a radio button's "onchange" event fire when the radio button is checked via an external function, and not by clicking on the radio button itself?
I have created a demo of my issue below, feel free to put the following in a text file and save it as .HTML:
This example demonstrates how the "onchange" event on radio buttons does not fire if the button is selected externally, i.e. by setting its "checked" value to "true".
You can test this by clicking one of the radio buttons invididually, then by clicking the "Select 1" or "Select 2" buttons.
The radio buttons have an "onchange" event registered such that an alert box should pop up when one of them is selected.
1:
2:
This is not a duplicate of How to trigger event in JavaScript?, and this is how:
If I were to fire the event manually, that would require me to look at the radio button and compared to the last time I looked at it, and fire the "onchange" event accordingly. The issue is that the radio button can be selected through a multitude of ways (click, keyboard press, touch/tap, external function etc) and rather than monitor each avenue of selection, I'd rather have the input element do that for me. If I can achieve what I am asking in the question, it will simplify this.
Answer
Use .click()
You should avoid using inline js.
No comments:
Post a Comment