开发者

jQuery Textarea focus

When I click a button I want the textarea in this li element to focus.

<li class="commentBlock" id="commentbox-79" style="display: list-item;">
  <div>
    <div class="grid userImageBlockS">
      <div class="imgSmall">
        <img width="35" height="35" alt="image" src="/bakasura1/files/images/small/1288170363aca595cabb50.jpg">
      </div>
    </div>
    <div class="grid userContentBlockS alpha omega"> 
      <form accept-charset="utf-8" action="/bakasura1/account/saveComment" method="post">
        <div style="display: none;">
          <input type="hidden" value="POST" name="_method">
        </div> 
        <input type="hidden" id="StatusMessageReplyPid" value="79" name="data[StatusMessageReply][pid]"> 
        <input type="hidden" id="StatusMessageReplyItemId" value="1" name="data[StatusMessageReply][item_id]"> 
        <input type="hidden" id="StatusMessageReplyCommentersItemId" value="1" name="data[StatusMessageReply][commenters_item_id]"> 
        <textarea id="StatusMessageReplyMessage" name="data[StatusMessageReply][message]">
          Write your comment...
        </textarea>
        <input type="submit" name="" value="Comment" class="comment" id="comment-79">
      </form> 
    </开发者_JAVA技巧div>
    <div class="clear"></div>
  </div>
</li>

This is my jQuery code:

$('.user-status-buttons').click(function() {
    var id = $(this).attr('id');
    $("#commentbox-"+id).slideToggle("fast");
    $("#commentbox-"+id+" #StatusMessageMessage").focus();
    return false;
});


I use timer to focus text areas :

setTimeout(function() {
 $el.find('textarea').focus();
}, 0);


Based on your comment in reply to Jacob, perhaps you want:

$('.user-status-buttons').click(function(){

    var id = $(this).attr('id');
    $("#commentbox-"+id).slideToggle("fast", function(){
        $("#commentbox-"+id+" #StatusMessageReplyMessage").focus();
    });

    return false;
});

This should give the #StatusMessageReplyMessage element focus after the slide effect has finished.


The easiest solution is to use jQuery focus

  $('#StatusMessageReplyMessage').focus();

NOTE: if you are testing this in the console, Chrome will send the focus back to the console! This can lead you to believe it had not worked when in fact it works perfectly. Just be aware of other focus grabbing scripts/behavior in your environment and it will all be fine :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜