Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery input select all on focus

Tags:

jquery

input

I'm using this code to try and select all of the text in the field when a user focuses on the field. What happens is, it selects all for a second, then its unselected and the typing cursor is left where I clicked...

$("input[type=text]").focus(function() {    $(this).select(); }); 

I want it all to remain selected.

like image 718
Tim Avatar asked Jun 30 '10 14:06

Tim


People also ask

How do you select all text in input on focus?

select to select all the text in the input as the value of the onFocus prop. e. target is the input element so we can call select on it to select all the text.

How can input focus in jQuery?

Using jQuery With jQuery, you can use the . focus() method to trigger the “focus” JavaScript event on an element. This method is a shortcut for . trigger("focus") method.

How do you focus an input element on page load?

The autofocus attribute is a boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads.


2 Answers

Try using click instead of focus. It seems to work for both mouse and key events (at least on Chrome/Mac):

jQuery < version 1.7:

$("input[type='text']").click(function () {    $(this).select(); }); 

jQuery version 1.7+:

$("input[type='text']").on("click", function () {    $(this).select(); }); 

Here is a demo

like image 137
karim79 Avatar answered Sep 25 '22 16:09

karim79


I think that what happens is this:

focus()    UI tasks related to pre-focus    callbacks        select()    UI tasks related to focus (which unselect again) 

A workaround may be calling the select() asynchronously, so that it runs completely after focus():

$("input[type=text]").focus(function() {      var save_this = $(this);     window.setTimeout (function(){         save_this.select();      },100); }); 
like image 37
Piskvor left the building Avatar answered Sep 23 '22 16:09

Piskvor left the building