views:

4472

answers:

1

I want to use the JavaScript select() function to highlight a text field on a form, but first I want to use a named anchor so the page will scroll to the proper section. The following code works pretty well in Firefox, (Unless you enter the same value twice,) but IE does not allow the highlighted text to be typed over (without a tab or a click) the second time the page loads. How can I work around this, or am I doing it wrong?

filename: Test.html

<HTML>
<HEAD>
    <script>
    function setFocus() {   
        document.AForm.AText.select();
    }
    </script>

</HEAD>

<BODY onLoad="setFocus();">
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br>

    <a name="ATag"></a>
    <form name="AForm" id="AForm" action="Test.html#ATag" method="get">        
        <input type="text" name="AText" id="AText" value="Enter text here." >
        <input type="submit" value="OK">
    </form>

</BODY>
</HTML>
+1  A: 

As far as I can tell this appears to be a bug in IE. It seems to be timing related. I found a work around but it is not very elegant and sheds no light to me on what might be wrong.

Perhaps another user will gain some insight from my work around. In any event this works for me:

function setFocus() {
  setTimeout(tryFocus,100);
}

function tryFocus() {
  document.AForm.AText.select();
}

As a bonus, the problem with FireFox not working when you send the same value twice in a row is that it's not sending your second GET because it's identical to the previous GET. You need a cache buster. So change your form to look like this:

<form name="AForm" id="AForm" action="index.html#ATag" method="get" onsubmit="bustCache();">
  <input type="text" name="AText" id="AText" value="Enter text here." >
  <input type="hidden" name="AHidden" id="AHidden" value="">
  <input type="submit" value="OK">
</form>

Change your script to this:

function setFocus() {
  setTimeout(tryFocus,100);
}

function tryFocus() {
  document.AForm.AText.select();
}

function bustCache() {
  document.AForm.AHidden.value = (new Date()).getTime();
}

This is far from perfect, but should work for your purposes.

Benry