hybrid
hybrid

Reputation: 3968

How to focus on textarea based on click?

I have some code that when a user clicks on a link "Add Comment", it looks a certain named div next to it and slidetoggles down that div. Inside of that div I have a textarea.

My goal is to set the focus on the textarea when the user clicks the "Add Comment" link. The problem I'm running into is I will have multiple comments/textareas/add comment links and I need it so when you click on "Add Comment" it focuses on the corresponding textarea.

Heres what I have so far:

jQuery

$(".add-comment-btn").click(function(){
    $(this).next(".inline-comment-form").slideToggle(200);
    $(this).next(".inline-comment-form textarea").focus();
    return false;
});

HTML

<a class="add-comment-btn" href="#">Add Comment</a>         

<div class="inline-comment-form">
<form action="" method="post">
        <div class="textarea">
            <textarea class="inline-comment-textarea" name="comment-textarea"></textarea>
        </div>
        <input value="SUBMIT" name="submit-inline-comment" class="form-btn" type="submit">

    </form>
</div><!--/Inline Comment Form -->  

Edit: I updated the code to add the Add Comment link and moved the return false

Upvotes: 0

Views: 6603

Answers (2)

James Montagne
James Montagne

Reputation: 78730

http://jsfiddle.net/Frgxv/

$(".add-comment-btn").click(function(){
    $(this).next(".inline-comment-form").slideToggle(200)
           .find("textarea").focus();

    return false;
});

next only works with siblings, the textarea isn't a sibling.

Upvotes: 4

jackrugile
jackrugile

Reputation: 1663

Hey, give this a try: http://jsfiddle.net/jackrugile/XNkES/

I am using the following code that seems to work:

$(this).next(".inline-comment-form").slideToggle(200).find('textarea').focus();

Upvotes: 1

Related Questions