How to set focus on input field using jQuery

Given the following HTML structure:

<div class="wrapper"> <div class="top"> <a href="http://example.com" class="link">click here</a> </div> <div class="middle"> some text </div> <div class="bottom"> <form> <input type="text" class="post"> <input type="submit"> </form> </div> <div> 

which will be repeated several times on the page, how to set the focus on the input field in the .bottom div when the user clicks on the link in the .top div?

I am currently making the .bottom div a successful .bottom using the jQuery code below, but cannot figure out how to set the focus on the input field at the same time.

 $('.link').click(function() { $(this).parent().siblings('div.bottom').show(); }); 

Thank!

+96
jquery html
Jul 18 2018-11-18T00:
source share
4 answers

Try this to set focus on the first input field:

 $(this).parent().siblings('div.bottom').find("input.post").focus(); 
+120
Jul 18 '11 at 20:08
source share

Justin's answer didn’t work for me (Chromium 18, Firefox 43.0.1). jQuery .focus() creates a visual selection, but the text cursor does not appear in the field (jquery 3.1.0).

Inspired by https://www.sitepoint.com/jqueryhtml5-input-focus-cursor-positions/ , I added an autofocus attribute to the input field and voila!

 function addfield() { n=$('table tr').length; $('table').append('<tr><td><input name=field'+n+' autofocus></td><td><input name=value'+n+'></td></tr>'); $('input[name="aa"'+n+']').focus(); } 
+7
Aug 21 '16 at 7:12
source share

If input occurs in a modal boot dialog, the answer will be different. Copying from How to set the focus on the first text input in the bootstrap modal after showing, here is what is required:

 $('#myModal').on('shown.bs.modal', function () { $('#textareaID').focus(); }) 
+5
Feb 15 '19 at 18:41
source share
 $('input').attr('autofocus', 'true'); 
0
Jul 19 '19 at 19:27
source share



All Articles