How to Set Focus on Input Field using JQuery

rolling stone picture rolling stone · Jul 18, 2011 · Viewed 273.3k times · Source

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!

Answer

Justin Ethier picture Justin Ethier · Jul 18, 2011

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

$(this).parent().siblings('div.bottom').find("input.post").focus();