jQuery Textarea focus

試著忘記壹切 提交于 2019-12-03 23:51:33

问题


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> 
    </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;
});

回答1:


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.




回答2:


I use timer to focus text areas :

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



回答3:


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 :)



来源:https://stackoverflow.com/questions/4191200/jquery-textarea-focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!