3

I am trying to provide support for browsers which don't have support for the autofocus attribute, using an approach something like this:

<input type="text" autofocus/>
<input type="text" autofocus="autofocus"/>
<input type="text"/>​

<script type="text/javascript">
    $("input[autofocus]").first().focus();
</script>

However, that selector is returning all input elements for IE7, including ones that don't have an 'autofocus' attribute. Its working for IE8+, and I have tested using jQuery 1.6.4, 1.7.2 and 1.8.2. I have a jsfiddle here: http://jsfiddle.net/HSC7K/4/.

These jQuery tickets seems related, but have been closed:

http://bugs.jquery.com/ticket/5637

http://bugs.jquery.com/ticket/7874

Edit: updated jsfiddle: http://jsfiddle.net/HSC7K/6/

Barry Pitman
  • 3,087
  • 1
  • 24
  • 32
  • If you're using HTML5 you'll need to include one of the shiv's to allow elements like autofocus. Have you done that? – Jay Blanchard Dec 17 '12 at 13:07
  • I'm using custom attributes, not HTML5 elements, so AFAIK it doesn't require a shiv. I've updated the fiddle to show that custom attributes are working, but if the attribute is called 'autofocus', it doesn't work. – Barry Pitman Dec 17 '12 at 13:47
  • Custom attributes are not valid in XHTML - what is your doctype? http://stackoverflow.com/questions/2413147/are-custom-attributes-ok-in-xhtml Autofocus is new in HTML5 – Jay Blanchard Dec 17 '12 at 13:53
  • I'm using the HTML5 doctype - . http://stackoverflow.com/questions/2412947/do-html5-custom-data-attributes-work-in-ie-6. True, autofocus is not natively supported in IE<10, hence I'm trying to provide a shim. Please check the jsfiddle. – Barry Pitman Dec 17 '12 at 14:17
  • 1
    Have you tried something like this; $('[autofocus]:not(:focus)').eq(0).focus(); – Jay Blanchard Dec 17 '12 at 14:22

1 Answers1

1

I hit this same issue trying to autofocus after an AJAX call.

$("input[autofocus]").first().focus();

Just doesn't work. I'm using IE 11. I found if you remove the input selector it works. So....

$("[autofocus]").first().focus();
RitchieD
  • 1,831
  • 22
  • 21