开发者

jQuery focus on content of input / textarea - not working properly in IE8

I want the input fields on my site to select all the text when the user first clicks on them, but in IE8 the text is selected for a split second then reverts back to normal. Works fine in FF.

My js code:

$(document).ready(function () { //HTML DOM document is ready
    // Add this behavior to all text fields
    $("input[type='text'], textarea").live("focus", function(){
                                         // Select field contents
                                         this.select();
                                         });
});

A开发者_StackOverflow社区ny ideas? I've tried adding ".focus()" after ".select()" and bizarrely enough it works, but throws loads of js errors in FF and IE.

Thanks


Try .select() on a jQuery object instead of the DOM element, and change the event to click. When you tab into the field, the text should be selected by default.

$("input[type='text']").live("click", function(){
       // Select field contents
      $(this).select();
  });

Well, this one was kicking me in the rear for some reason. I could swear I've done this before, but couldn't figure it out how.

This is the best I came up with. It postpones the .select() using setTimeout() until after the click event fires. Maybe there's a better way? Hope it helps.

$('input[type=text]').live('focus', function() {
    var $th = $(this);
    setTimeout(function(){$th.select();}, 50);
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜