0

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.
lurker
  • 56,987
  • 9
  • 69
  • 103

2 Answers2

3

You're already using JQuery's "ready" callback which determines when the document is loaded and DOM is ready for manipulation. You can just put your trigger event in there.

$(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()

  $('#foo_select').trigger('change')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="foo_select"></select>
<p id="text"></p>
Soviut
  • 88,194
  • 49
  • 192
  • 260
  • Tried that (putting the trigger in the `ready` event) already. It doesn't work. Same symptoms. Per [this question and answer](https://stackoverflow.com/questions/4584373/difference-between-window-load-and-document-ready-functions), the `ready` event means the DOM is ready, but not necessarily *all the content*. – lurker Apr 17 '19 at 23:41
  • All the code is exactly as shown in my question. No other libraries. – lurker Apr 17 '19 at 23:45
  • 1
    When the DOM is ready is means the document is fully loaded and all elements are available for manipulation. window.onload does NOT guarantee the same. I've updated my answer to include a working piece of code, making sure to put the trigger at the end of the ready block (since you empty the text output first) – Soviut Apr 17 '19 at 23:51
  • Thanks. From what I've read, "DOM ready" means the structure is all in place, but not all of the elements may be loaded (e.g., images download, etc). My further understanding, based upon what I've read, is that the windows.onload comes later and when all of the elements have been fully populated. Can you point to the documentation supporting what you're indicating? It seems confusing. I did try your change (which I had sworn I tried before) and it does seem to work. I'm going to try it again with my full, real code tomorrow to double-check. – lurker Apr 17 '19 at 23:54
  • Soviut's answer is spot on, the best place to trigger the change event is inside your $(document).ready, after having defined what you do when your select changes. – ludovico Apr 18 '19 at 00:02
  • window.load vs $(document).ready: https://stackoverflow.com/questions/3698200/window-onload-vs-document-ready/3698214 – ludovico Apr 18 '19 at 00:02
  • @ludovico the link you provide reflects my understanding of the two events: *The `ready` event occurs after the HTML document has been loaded, while **the `onload` event occurs later**, when all content (e.g. images) also has been loaded.* Although there's perhaps a simpler approach, why is the on load in my case not working? I can put an alert in the event and confirm the event fires. It's just not setting the `div`. – lurker Apr 18 '19 at 00:11
  • Correct, the load event occurs when all content has been loaded (including images, scripts, sub-frames...). In theory window.onload will always fire after $(document).ready but there's no need to use window.onload. Soviut's answer is completely correct. If it doesn't work it might be due to a different problem in the rest of your code. – ludovico Apr 18 '19 at 00:44
  • --clarifying: why I say that "in theory" window.onload will always fire after $(document).ready why I say https://stackoverflow.com/questions/40608801/why-does-window-onload-event-occur-before-document-ready (this is a rare exception and, most likely, it doen't apply in your case) – ludovico Apr 18 '19 at 00:47
  • @ludovico that was my quandry. Everything I read (except that last link you showed) indicated that, not only should it have worked for me in this case, but it was even the desired way to implement it to assure the proper sequence of events. – lurker Apr 18 '19 at 01:07
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/192014/discussion-between-ludovico-and-lurker). – ludovico Apr 18 '19 at 02:18
  • @ludovico you shouldn't be using `$(document).ready()` since about 2010. It's a slower operation since it unnecessarily wraps the document. Use `$(function() { ... })` – Soviut Apr 18 '19 at 03:04
  • @lurker if your page has no images or other content to load beyond your script, it may trigger as soon as the DOM is ready, but before the script has parsed. This could be an optimization since script parsing requires a repaint. This is a theory, but that's the reason JQuery has a "ready" event in the first place; It was really hard to track when a script should load from the – Soviut Apr 18 '19 at 03:08
  • Thanks. The page has some Ajax fetching going on but not image loading. The change you suggested seems to work fine. I was under the impression, based upon my interwebs reading, that "on load" was needed to ensure execution after "ready". Evidently that's not always reliable. – lurker Apr 18 '19 at 12:24
1

Why don't you simply 'trigger' it when creating the options?
Is there any benefit to triggering it after the document has loaded?

If not, simply apply the 'starting value', from the start.

This would also imply moving your script after the HTML Markup, just before the closing </body> tag - in order for the #text div to exist in the DOM at the time of execution.

// use this
$('#text').text($('#foo_select').val())
// instead of
$('#text').empty()

(hope the code is right, I don't use JQuery - but you get message :) )

Andu Andrici
  • 853
  • 1
  • 5
  • 12
  • This is a simplified code example. My actual code is a little more complex. But I will rethink what I'm doing based upon your comments. Maybe I don't actually need to trigger the change and can do something more directly. I'm still in a quandary as to why what I have doesn't work, thogh. – lurker Apr 18 '19 at 00:12