开发者

Javascript focus and select not working in FF

Using jQuery, the following is not working in FF, but it is in IE

$(this).focus().select();

I looked around for this and found that you could use a timeout to get around this, but that is not something I want to do if I can avoid it. Do开发者_Go百科es anyone know another way to do this and have it work in FF?

Metropolis


I've run into this before as well. I believe that the setTimeout() solution is the only way this will work in Firefox. The issue has to do with order of events processing, if I remember correctly: IE immediately changes control focus when the focus() method is invoked, but Firefox handles it by adding a focus event to the event queue, which doesn't resolve until after the current event processing has completed. The setTimeout() trick works because it adds the remainder of your code to another event to the event queue after the focus change event, causing it to resolve before your code continues processing.


Please try this code

setTimeout(function() 
 {
   $(Selecter).focus(); 
 }, 0);


i used

$('input').focus().select();

on

 <input type="text" value="Some text" />

and it worked in firefox. maybe I dont understand what your problem exactly is.


A solution to this that I just found is to use the below code.

[elementHere].setSelectionRange(0, [elementHere].value.length);

According to the Mozilla Developer Network documentation, this selects the text but does not focus it. At least for me, this prevented issues with selecting text inside a focus event handler, since selecting the text does not cause the element containing it to be focused again.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜