views:

36

answers:

1

Run this in IE 7,8 or 9.

<!DOCTYPE html>
<html>
<head>
    <meta charset=utf-8>
    <title>IE input value</title>
</head>
<body>
    <form action="">
        <input id="test" type="text" name="username">
    </form>
    <script>
        var input = document.getElementById("test");
        alert(input.value);
        setTimeout(function() {

            alert(input.value);
        }, 2000);
    </script>
</body>
</html>

If you enter a value manually, then hit "refresh", the first alert is empty, the second alerts whatever you typed, so it seems IE takes a little longer to "auto-populate" the field again.

Question: is anyone else experiencing this and if so: is there a better way than using setTimeout here?

BTW: Firefox alerts what you typed two times (as I would expect).

+1  A: 

Yes, this is known IE behaviour.

Unfortunately, browsers implement form value memory differently:

  • Mozilla and WebKit replace the HTML value with the remembered value as soon as the element is loaded into the document;
  • IE replaces the value when the document content is completely loaded;
  • Opera replaces the value just after document content is loaded, possibly after the load event fires on window.

(There are also browser differences about under what circumstances a reload causes form fields to be remembered, and browsers with bfcache will cause field memory to happen less as more back/forward navigations bypass page reloading.)

Aggravatingly, that means if you want to write a script that checks form values and updates page content dependent on them reliably, you have to schedule a 0-delay timeout from window.onload—and, if you want it to react faster than onload, before that too (eg. straight away and/or on a poller).

bobince
Thanks, I feel a little less insane now.
Daniel