1

(I have already asked this question; here I am adding more details)

I have return a jQuery which returns the text entered in input element on change event. This jQuery works fine in FireFox but fails in Internet Explorer (IE9).

  <script>
      $(document).ready(function () {
          $("#UserName").change(function () {
              alert("Text Entered Is :"+$("#UserName").val());
          });
      });
  </script>

1) I am using ASP.NET MVC; to reach the page having above jquery I am using Html.ActionLink

2) On IE when I reach on the page of above jQuery it does not work; but when I press F5 and refresh the page it works.

3) On Firefox I do not need to refresh the page; it works on very first attempt.

Please help...

tereško
  • 58,060
  • 25
  • 98
  • 150
  • are you sure you dont have a prev version of the page cached? What version of jquery? This code looks correct – Glenn Ferrie Feb 22 '13 at 12:34
  • This code is not correct, document ready should not be used with jQuery Mobile, sometimes document ready can trigger before page is created and int his case change event is not going to be bound. Take a look at my other answer for a better understanding: http://stackoverflow.com/a/14469041/1848600 – Gajotres Feb 22 '13 at 12:42
  • @Gajotres I don't see **NewToAspMVC** mentioning anything about JQueryMobile. – Binaek Sarkar Feb 22 '13 at 13:24
  • And what about used tag? – Gajotres Feb 22 '13 at 14:03

1 Answers1

0

The $(document).ready() event depends on an event called DOMContentLoaded (in Chrome, not really sure about firefox, but it is there by some name).

This event is fired as soon as the HTML has been loaded and all the relevant files have been brought in (the CSS and the JS files).. Chrome, Safari (WebKit) and Firefox(Gecko) are pretty predictable at firing this particular event. It bubbles up the stack like clockwork and once caught, you can play fiddle with it, for all anyone cares.

However, as far as IE is concerned, up till version 7 (I think) they never implemented this event. Given that, the implementation in the recent versions is not so efficient as well.

I have faced this problem time and again.

One workaround for this that has worked everytime is to fire the event manually at the end of the HTML:

<script type="text/javascript">
try{jQuery.ready();}catch(e){}
</script>

Hope this helps

Edit
A great way of seeing whether the event gets fired is to add somekind of action in the code. SOmething like:

<script>
      $(document).ready(function () {
          alert("Loaded");
          $("#UserName").change(function () {
              alert("Text Entered Is :"+$("#UserName").val());
          });
      });
</script>

alert blocks the execution of the code, due the single threaded nature of Javascript. Therefore, you can use this to get a pseudo-stacktrace of your code.

Binaek Sarkar
  • 617
  • 8
  • 21