Metropolis
Metropolis

Reputation: 6622

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. Does anyone know another way to do this and have it work in FF?

Metropolis

Upvotes: 3

Views: 5981

Answers (4)

vestigal
vestigal

Reputation: 71

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.

Upvotes: 0

Akash Detroja
Akash Detroja

Reputation: 43

Please try this code

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

Upvotes: 3

Ali Habibzadeh
Ali Habibzadeh

Reputation: 11558

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.

Upvotes: 0

Dan Story
Dan Story

Reputation: 10155

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.

Upvotes: 7

Related Questions