-1

If I have two input fields, one with the autofocus attribute and one without, how do I focus on the one without the autofocus attribute on document load? For instance:

<script type="text/javascript">
$(document).ready(function() {
    // $("input[name=\"bar\"]").blur();
    // $("input[autofocus]").removeAttr("autofocus");
    $("input[name=\"foo\"]").focus();
});
</script>
<p><input name="foo" type="text"></p>
<p><input autofocus name="bar" type="text"></p>

When I load the page, the cursor is fixed on the second input field instead of the first. I have tried the commented out lines to try and fix this somehow but I have had no success.

Edit: I have tried the solution mentioned in the "duplicate question", which was to use .blur() on the element, but that did not work. Additionally, the duplicate question only answers how to disable the autofocus and does not answer how to re-focus on another input field afterwards.

  • Possible dublicate of http://stackoverflow.com/questions/6765681/disable-text-field-autofocus-in-javascript – Andrew Surzhynskyi May 03 '15 at 19:27
  • @Applejack for some reason, the solutions in mentioned question (which were to use ".blur()" and also to ".focus on an object further on") did not work for me when I tried. – takeshibaconsuzuki May 03 '15 at 19:31

1 Answers1

1

After spending some more time with this, I finally figured out that 'focus' was firing too early. To solve this problem, all I had to do was wrap it in a settimeout:

setTimeout(function() {
    $("#myTags input[type=\"text\"]").focus();
}, 20);
$("input[autofocus]").blur();