I am using Microsoft Edge 44.17763.1.0, Microsoft EdgeHTML 18.17763.
I'm having trouble getting Edge to trigger a select option change event when a page is loaded.
I have a select drop down box which, when contents change, automatically populates a div with the selected text. What I want is for this page to do this automatically when it is first loaded. That is, the page loads, initializes the select drop down box, then automatically populates the div with the existing selection without having to click on it.
The jquery will automatically update the div on an .change event for the select drop down. This works fine when the user changes the select box contents with the mouse. The select options are initialized when the page is first opened, so I put the select option initialization in the $(document).ready event, and then I want to trigger select change event automatically when the page loads but after the select drop down has been initialized, so I put the trigger in the $(window).on('load', ... event.
<html>
<head>
<title>Test</title>
<script language="javascript" type="text/javascript" src='/script/jquery-3.4.0.min.js'></script>
<script language="javascript" type="text/javascript">
$(function () {
var entries = ['fred', 'barney', 'betty', 'wilma'];
$.each(entries, function() {
$('#foo_select').append($("<option />").val(this).text(this));
});
$('#foo_select').change(function() {
$('#text').text($(this).val())
})
$('#text').empty()
})
$(window).on('load', function() {
$('#foo_select').trigger('change')
})
</script>
</head>
<body>
<select id='foo_select'>
</select>
<p>
<div id='text' style='width: 100px'></div>
</p>
</body>
</html>
I wrote the code this way based upon information I've read regarding these two events, and which is summarized in Difference between window load and document ready functions and Windows onload vs document ready. This code works fine in Firefox and Chrome. It does not, however, work in Microsoft Edge. I did determine that the load event fires in Edge, it just appears (perhaps) to be too soon, as in before the drop down is initialized, so the trigger action does nothing.
Based upon what I want to do here, is this the incorrect approach, or is there an issue with Edge?
ADDENDUM: A couple of good answers have given me some alternatives, but the question still remains as to why the
load event in the original doesn't work in this context.