Javascript: cross-browser solution for selecting all text inside a text box in focus

I perform the following functions:

  • user clicks on or tabs in text box
  • all text in the text box is selected if the text box no longer has focus, in which case the default click / select function should be performed

Is it possible?


This works in Firefox 5
$('input[type="text"]').live('focus', function () { this.select(); }); 

http://jsfiddle.net/HmQxZ/13/

Chrome and IE8 only select all text in a second


It works * in Chrome
 $('input[type="text"]').live('click', function () { this.select(); }); 

http://jsfiddle.net/HmQxZ/12/

Firefox and IE8 selects all the text, but the next time you click, the text remains selected.

* type of work, after the text field has focus, clicking on it alternates between selecting the entire text and the possibility of clicking where the blinking carriage is going. This is probably acceptable.

+6
source share
4 answers

Just tighten it for a millisecond using setTimeout :

 $('input[type="text"]').live('focus', function() { var inp = this; setTimeout(function() { inp.select(); }, 1); }); 

http://jsfiddle.net/HmQxZ/14/

What happens is some other event in the browser - this is the highlight setting after you select the text. So, waiting for the milliseconds, you end all browser events, and then select the text. Nothing will cancel it now.

+9
source

You can add

 event.preventDefault(); return false; 

to your function (first). This may fix other browsers.

Also, add event to the sig function:

 $('input[type="text"]').live('focus', function (event) { 
0
source

You must remember return false; event.stopPropagation(); event.preventDefault() return false; event.stopPropagation(); event.preventDefault() return false; event.stopPropagation(); event.preventDefault() like this:

 $('input[type="text"]').live('click', function (event) { this.select(); event.stopPropagation(); event.preventDefault(); return false; }); 

http://jsfiddle.net/7rYLV/

0
source

If you can use jQuery, you can do something like:

 $("#myInputField").focus(function(){ // Select input field contents this.select(); }); // Add this behavior to all text fields $("input[type=text]").focus(function(){ // Select field contents this.select(); }); 

Taken from HERE

0
source

Source: https://habr.com/ru/post/893730/


All Articles