124

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 do I set the focus on the input field in the .bottom div when a user clicks on the link in the .top div?

I am currently making the .bottom div appear successfully on click using the JQuery code below, but can't seem to figure out how to set focus on the input field at the same time.

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

Thanks!

rolling stone
  • 12,668
  • 9
  • 45
  • 63

4 Answers4

156

Try this, to set the focus to the first input field:

$(this).parent().siblings('div.bottom').find("input.post").focus();
Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
  • 1
    Space between `input` & `:first`. Does jQuery splice that automatically? I've always thought it should be `input:first`. – simshaun Jul 18 '11 at 20:11
  • Yes, you can write it either way. I suppose `input:first` might be the more formal way to write it, although it seems easier to read the other way. But maybe that's just me :) – Justin Ethier Jul 18 '11 at 20:17
  • I guess that because I'm so used to it, when I see the space I automatically think "child element" and it takes a second to de-confuse myself. But hey, that's just me. It's cool that it works either way. – simshaun Jul 18 '11 at 20:19
  • @justin i actually had to tweak it a little to make it work: `$(this).parent().siblings('div.bottom').find("input.post").focus();` but `.find()` is the selector I was looking for. Interestingly `input :first` nor `input:first` worked. – rolling stone Jul 18 '11 at 20:26
  • Interesting, probably because the input is within a `form` tag. Anyway, glad you go it to work! – Justin Ethier Jul 18 '11 at 20:27
  • jQuery's .focus() function is for adding a handler for the event emitted when the input gets the focus. This does not set focus on an input. Downvoted. – Kevin Buchs Feb 15 '19 at 14:17
  • @KevinBuchs - It can either bind an event handler to the "focus" JavaScript event, or trigger that event on an element. Read the [documentation](https://api.jquery.com/focus/) for the third variation of `focus` and see the example at the bottom. – Justin Ethier Feb 15 '19 at 14:52
26

If the input happens to be in a bootstrap modal dialog, the answer is different. Copying from How to Set focus to first text input in a bootstrap modal after shown this is what is required:

$('#myModal').on('shown.bs.modal', function () {
  $('#textareaID').focus();
})  
Kevin Buchs
  • 2,520
  • 4
  • 36
  • 55
8

Justin's answer did not work for me (Chromium 18, Firefox 43.0.1). jQuery's .focus() creates visual highlight, but 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 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();
}
MKaama
  • 1,732
  • 2
  • 19
  • 28
  • 1
    Worked for me. Simpler version is like this: $('.class input').focus(); $('.class input').prop('autofocus'); – ejntaylor Jul 25 '17 at 10:55
2
//$GLOBALS['sitename'] is our domain site URL
//$_GET['s'] is the search parameter of our search, and we want to highlight that term searched...    
jQuery(document).ready(function($){  
        let loc=location.href;
        switch(loc) 
        {

    case "<?php echo $GLOBALS['sitename'] ?>?s=<?php echo $_GET['s'] ?>":       
        {       
        let searchf= $("form.search-form").find("input[type='search']:first");
//searchf.val('').focus();      
//empty the value to allow a new search and focus on the field....this works but better to highlight the searched term to allow the user to decide if want to type in something else or just hit again search. In case we want to empty the searched term 
           setTimeout(function (){
           searchf.delay(1000).focus().select(); 
           }, 1000);    
        break;
//.... end of relevant code 
        }

            
Jean G.T
  • 1
  • 10
  • 25