Javascript select () function with named anchor

I want to use the JavaScript select () function to select a textbox on a form, but first I want to use a named anchor to make the page jump to the appropriate section. The following code works very well in Firefox (unless you enter the same value twice), but IE does not allow you to type the selected text (no tab or click) the second time the page loads. How can I get 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


source to share


1 answer


As far as I can tell, this seems to be a bug in IE. This seems to be due to time constraints. I found a job, but it is not very elegant and does not shed light on me, which may be wrong.

Perhaps another user will get some idea of โ€‹โ€‹my work. This works for me anyway:

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

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

      

As a bonus, the issue with FireFox doesn't work when you send the same value twice in a string is that it doesn't send your second GET because it is identical to the previous GET. You need a cache bitter. So change the shape so it looks 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 the following:

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

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

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

      

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

+1


source







All Articles