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:
<!DOCTYPE html>
<html>
<body>
<p>
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".
<br />
You can test this by clicking one of the radio buttons invididually, then by clicking the "Select 1" or "Select 2" buttons.
<br />
The radio buttons have an "onchange" event registered such that an alert box should pop up when one of them is selected.
</p>
1: <input type="radio" value="1" id="1" name="myradio" onchange="myFunction()" /> <input type="button" value="Select 1" onclick="document.getElementById('1').checked=true;" /><br />
2: <input type="radio" value="2" id="2" name="myradio" onchange="myFunction()" /> <input type="button" value="Select 2" onclick="document.getElementById('2').checked=true;" />
<script>
function myFunction() {
alert("A radio button was selected.");
}
</script>
</body>
</html>
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.