346

What is a Vanilla JS or jQuery solution that will select all of the contents of a textbox when the textbox receives focus?

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Jon Erickson
  • 112,242
  • 44
  • 136
  • 174
  • See [_"Selecting text on focus using jQuery not working in Safari and Chrome"_](http://stackoverflow.com/a/5044224/601179) as well. – gdoron Dec 21 '12 at 08:58
  • 3
    @gdoron for some reason that link redirects to this question itself. – Destrictor May 30 '13 at 13:01
  • @Destrictor, Yes, it should have been this: ["Selecting text on focus using jQuery not working in Safari and Chrome"](http://stackoverflow.com/questions/1269722/selecting-text-on-focus-using-jquery-not-working-in-safari-and-chrome) – gdoron May 30 '13 at 18:54
  • The problem with most of these solutions is that they do not work correctly when changing the cursor position within the input field. Take a look at my answer here: http://stackoverflow.com/a/20826207/641452 – Colin Breame Dec 29 '13 at 14:15

24 Answers24

390
$(document).ready(function() {
    $("input:text").focus(function() { $(this).select(); } );
});
John Sheehan
  • 77,456
  • 30
  • 160
  • 194
  • 26
    Also just for extra info: "input[type=text]" now can be "input:text" regards – Ricardo Vega Jan 26 '09 at 22:29
  • 8
    This doesn't seem to work for me on Chrome and the jQuery website says it is browser dependent. Can anyone else verify? – Kenny Wyland Sep 13 '12 at 20:21
  • 71
    It looks like WebKit browsers interfere with this because of the mouseup event. I added this and it worked: $('input:text').mouseup(function(e) { return false; }); – Kenny Wyland Sep 13 '12 at 20:25
  • 5
    Kenny is correct, but unfortunately 'mouseup' also affects Chrome spinner controls. Triggering off 'click' rather than 'focus' seems to solve that – Richard Kennard Sep 12 '13 at 21:46
  • 24
    I use like this: $("input:text").select().focus(); – Phuong Dec 26 '13 at 04:22
  • @RichardKennard, but wouldn't a spinner have `type="number"` not `type="text"`? One downside of the `mouseup` approach is in comment to Zach's answer (by enigment): "once the cursor is in the field, clicking somewhere within the selected text to position the cursor there doesn't work; clicks are effectively disabled." – JohnK Mar 04 '14 at 19:02
  • 5
    `$("input:text").focus().select();` seems to work. Is there a reason it's not this simple? – Nate Nov 17 '14 at 20:18
  • 3
    As @Kenny's comment webkit dose indeed interfere. I ended up using this: `$("input:text").on('mouseup', function() { $(this).select(); });` Works fine in the latest IE, chrome and firefox browsers. – Matthew Marlin Mar 23 '15 at 21:48
  • 2
    Using `this.select()` is faster. [It's vanilla](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select). – Mooseman Jul 27 '15 at 10:50
  • `focus` seems to be working in webkit now, at least in my tests. The issue with `mouseup` is that it doesn't work if the user tabs into the input. It also prevents the user from moving the caret with the mouse. – AJ Richardson Apr 06 '16 at 20:47
275

<input type="text" onfocus="this.select();" onmouseup="return false;" value="test" />
caesay
  • 16,932
  • 15
  • 95
  • 160
Zach
  • 24,496
  • 9
  • 43
  • 50
  • 49
    + onmouseup="return false" to stop deselect on click – Anthony Johnston Jun 15 '12 at 07:27
  • 2
    +1 for some kind of stopEvent for mouseup, or this doesn't work reliably. The downside of doing that is that once the cursor is in the field, clicking somewhere within the selected text to position the cursor there doesn't work; clicks are effectively disabled. Still, for situations where selecting the whole text on focus is desirable, it's probably the lesser of two evils. – enigment Aug 30 '12 at 13:23
  • I was able to somewhat get around the issue raised by enigment by setting a global variable doMouseUp to false, during the onMouseDown event, if this != document.activeElement. Then, during onMouseUp, reset doMouseUp to true and return the doMouseUp value before you reset it. This is getting convoluted and needs code - I'll post an answer explaining it better. – Travis Aug 21 '13 at 15:16
  • While separating script from markup, this is the most elegant way to auto-select `onfocus` for a single text field. If I were going to have more than one field where I wanted this auto-select functionality, I would create a script function and call it. – Slink May 04 '16 at 16:04
  • I don't get it. What's the difference between having `onmouseup="return false;"` and not having it? – ADTC Dec 13 '16 at 04:22
  • 4
    **Do NOT** add `onmouseup="return false;"` if you want the user to be able to freely select and edit the text _after_ focusing inside the textbox. With this code, the text will be locked into a "select all" situation and the user will not be able to edit it unless the user types in a new text or uses arrow keys to move around. Honestly this feels like a very weird behavior and wouldn't make sense unless the textbox is intended to be permanently non-editable (and therefore disabled). – ADTC Dec 16 '16 at 06:28
  • 1
    Technically, you don't need `onmouseup="return false;"` if you simply want the selection to occur when the user _first_ clicks or tabs. And +1 for the vanilla javascript! – clabe45 May 30 '18 at 23:53
47
$(document).ready(function() {
  $("input[type=text]").focus().select();
});
Tomas Kirda
  • 8,347
  • 3
  • 31
  • 23
39
$(document).ready(function() {
    $("input:text")
        .focus(function () { $(this).select(); } )
        .mouseup(function (e) {e.preventDefault(); });
});
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Yogesh Agrawal
  • 971
  • 10
  • 9
  • 1
    This is good. Thanks! The comment by enigment to Zach's answer gives one downside of preventing default of the `mouseup` event: "once the cursor is in the field, clicking somewhere within the selected text to position the cursor there doesn't work; clicks are effectively disabled. Still, for situations where selecting the whole text on focus is desirable, it's probably the lesser of two evils." – JohnK Mar 04 '14 at 19:11
28

jQuery is not JavaScript which is more easy to use in some cases.

Look at this example:

<textarea rows="10" cols="50" onclick="this.focus();this.select()">Text is here</textarea>

Source: CSS Tricks, MDN

Ritik Patni
  • 453
  • 4
  • 15
aaa
  • 305
  • 3
  • 2
22

This is not just a Chrome/Safari issue, I experienced a quite similar behavior with Firefox 18.0.1. The funny part is that this does not happen on MSIE! The problem here is the first mouseup event that forces to unselect the input content, so just ignore the first occurence.

$(':text').focus(function(){
    $(this).one('mouseup', function(event){
        event.preventDefault();
    }).select();
});

The timeOut approach causes a strange behavior, and blocking every mouseup event you can not remove the selection clicking again on the input element.

Cizar
  • 283
  • 2
  • 5
  • 2
    +1 for the usage of one to prevent a single mouseup. I really disliked not being able to select text with the mouse after the initial click. – Pluc Oct 16 '13 at 17:50
22

HTML :

var textFiled = document.getElementById("text-filed");
textFiled.addEventListener("focus", function() { this.select(); });
Enter Your Text : <input type="text" id="text-filed" value="test with filed text">

Using JQuery :

$("#text-filed").focus(function() { $(this).select(); } );

Using React JS :

In the respective component -

<input
  type="text"
  value="test"
  onFocus={e => e.target.select()}
/>
grepsedawk
  • 3,324
  • 2
  • 26
  • 49
Aniruddha Shevle
  • 4,602
  • 4
  • 22
  • 36
11

my solution is to use a timeout. Seems to work ok

$('input[type=text]').focus(function() {
    var _this = this;
    setTimeout(function() {
        _this.select();
    }, 10);
});
Jamie Pate
  • 1,783
  • 20
  • 18
  • This is the solution I use and prefer. I use a timeout value of 0 since that will cause it to be added to the end of the current event queue, which means it will run after the "mouseup" event. – DavidM Sep 18 '14 at 20:48
6

This will also work on iOS:

<input type="text" onclick="this.focus(); this.setSelectionRange(0, 9999);" />

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select

Kai
  • 417
  • 4
  • 15
4

I know inline code is bad style, but I didn't want to put this into a .js file. Works without jQuery!

<input type="text" value="blah blah" onfocus="this.select(); this.selAll=1;" onmouseup="if(this.selAll==0) return true; this.selAll=0; return false;"></input>
3

The answers here helped me up to a point, but I had a problem on HTML5 Number input fields when clicking the up/down buttons in Chrome.

If you click one of the buttons, and left the mouse over the button the number would keep changing as if you were holding the mouse button because the mouseup was being thrown away.

I solved this by removing the mouseup handler as soon as it had been triggered as below:

    $("input:number").focus(function () {
        var $elem = $(this);
        $elem.select().mouseup(function (e) {
            e.preventDefault();
            $elem.unbind(e.type);
        });
    });

Hope this helps people in the future...

H2Os
  • 31
  • 4
  • Nopes. u are giving a solution to a self-generated problem. If you look properly at the answer, they are binding `mouseup` to the **text** input fields only and not `number`s. This problem should not come therefore – Om Shankar Jul 03 '13 at 06:56
  • The problem with binding mouseup is that it interferes when moving the cursor within the field. This is a better solution, but if you tab into the field, then the next mousedown will be lost (and user will not be able to move the cursor with the mouse). That is better than losing all mousedowns! – Colin Breame Dec 29 '13 at 13:41
3

This will work, Try this -

<input id="textField1" onfocus="this.select()" onmouseup="return false" /> 

Works in Safari/IE 9 and Chrome, I did not get a chance to test in Firefox though.

3

Like @Travis and @Mari, I wanted to autoselect when the user clicked in, which means preventing the default behaviour of a mouseup event, but not prevent the user from clicking around. The solution I came up with, which works in IE11, Chrome 45, Opera 32 and Firefox 29 (these are the browsers I currently have installed), is based on the sequence of events involved in a mouse click.

When you click on a text input that does not have focus, you get these events (among others):

  • mousedown: In response to your click. Default handling raises focus if necessary and sets selection start.
  • focus: As part of the default handling of mousedown.
  • mouseup: The completion of your click, whose default handling will set the selection end.

When you click on a text input that already has focus, the focus event is skipped. As @Travis and @Mari both astutely noticed, the default handling of mouseup needs to be prevented only if the focus event occurs. However, as there is no "focus didn't happen" event, we need to infer this, which we can do within the mousedown handler.

@Mari's solution requires that jQuery be imported, which I want to avoid. @Travis's solution does this by inspecting document.activeElement. I don't know why exactly his solution doesn't work across browsers, but there is another way to track whether the text input has focus: simply follow its focus and blur events.

Here is the code that works for me:

  function MakeTextBoxAutoSelect(input)
  {
    var blockMouseUp = false;
    var inputFocused = false;

    input.onfocus =
      function ()
      {
        try
        {
          input.selectionStart = 0;
          input.selectionEnd = input.value.length;
        }
        catch (error)
        {
          input.select();
        }

        inputFocused = true;
      };

    input.onblur =
      function ()
      {
        inputFocused = false;
      };

    input.onmousedown =
      function ()
      {
        blockMouseUp = !inputFocused;
      };

    input.onmouseup =
      function ()
      {
        if (blockMouseUp)
          return false;
      };
  }

I hope this is of help to someone. :-)

Community
  • 1
  • 1
Jonathan Gilbert
  • 3,526
  • 20
  • 28
  • +1 Thanks, but how can this be re-written so that you don't hard-code the 'txtCustomer' control into the script? Is there a way to pass down a 'this' object? – Fandango68 Dec 16 '15 at 01:20
  • One way would be to create a utility function to apply the behaviour to any element, passed in as a parameter. Within that function, the element reference would be hard-coded -- to the parameter. You could then call it on any number of input elements, identified by whatever means you have at your disposal. :-) – Jonathan Gilbert Dec 17 '15 at 02:51
  • Sorry I am a noob. Could you please update your answer with an example? Thanks – Fandango68 Dec 17 '15 at 03:56
  • 1
    Just wrap the code I wrote in a function declaration that takes a parameter called "txtCustomer". I recommend renaming "txtCustomer" to something else, but if you're not confident in doing that, it will technically work with the variable named "txtCustomer". That is to say: function MakeTextBoxAutoSelect(txtCustomer) { **what I wrote above** } – Jonathan Gilbert Jan 11 '16 at 21:40
3

I know there are already a lot of answers here - but this one is missing so far; a solution which also works with ajax generated content:

$(function (){
    $(document).on("focus", "input:text", function() { 
        $(this).select(); 
    });
});
low_rents
  • 4,481
  • 3
  • 27
  • 55
2

I was able to slightly improve Zach's answer by incorporating a few function calls. The problem with that answer is that it disables onMouseUp completely, thereby preventing you from clicking around in the textbox once it has focus.

Here is my code:

<input type="text" onfocus="this.select()" onMouseUp="javascript:TextBoxMouseUp();" onMouseDown="javascript:TextBoxMouseDown();" />

<script type="text/javascript">
    var doMouseUp = true;
    function TextBoxMouseDown() {
        doMouseUp = this == document.activeElement;
        return doMouseUp;
    }
    function TextBoxMouseUp() {
        if (doMouseUp)
        { return true; }
        else {
            doMouseUp = true;
            return false;
        }
    }
</script>

This is a slight improvement over Zach's answer. It works perfectly in IE, doesn't work at all in Chrome, and works with alternating success in FireFox (literally every other time). If someone has an idea of how to make it work reliably in FF or Chrome, please share.

Anyway, I figured I'd share what I could to make this a little nicer.

Travis
  • 1,044
  • 1
  • 17
  • 36
  • There is an error in your code - the second method should be called "TextBoxMouseUp". Take a look at my answer which uses a similar approach. – Colin Breame Dec 29 '13 at 14:21
  • 1
    It should be noted that `onMouseUp=""` and `onMouseDown=""` are not the correct w3 standard. They should be `onmouseup=""` and `onmousedown=""`. As with other html attributes, they should are written in lowercase not in camel case. – DrewT Mar 12 '15 at 05:40
2

What is a JavaScript or jQuery solution that will select all of the contents of a textbox when the textbox receives focus?

You only need to add the following attribute:

onfocus="this.select()"

For example:

<input type="text" value="sometext" onfocus="this.select()">

(Honestly I have no clue why you would need anything else.)

ADTC
  • 8,999
  • 5
  • 68
  • 93
1

This worked for me (posting since it is not in answers but in a comment)

 $("#textBox").focus().select();
Vijay Vepakomma
  • 733
  • 6
  • 9
0
onclick="this.focus();this.select()"
Brian Mains
  • 50,520
  • 35
  • 148
  • 257
Sourabh
  • 4,186
  • 2
  • 17
  • 16
0
$('input').focus(function () {
    var self = $(this);
    setTimeout(function () {
        self.select();
    }, 1);        
});

Edit: Per @DavidG's request, I can't provide details because I'm not sure why this works, but I believe it has something to do with the focus event propagating up or down or whatever it does and the input element getting the notification it's received focus. Setting the timeout gives the element a moment to realize it's done so.

MikeT
  • 2,530
  • 25
  • 36
0

If you chain the events together I believe it eliminates the need to use .one as suggested elsewhere in this thread.

Example:

$('input.your_element').focus( function () {
    $(this).select().mouseup( function (e) {
        e.preventDefault();
    });
});
DrewT
  • 4,983
  • 2
  • 40
  • 53
0

Note: If you are programming in ASP.NET, you can run the script using ScriptManager.RegisterStartupScript in C#:

ScriptManager.RegisterStartupScript(txtField, txtField.GetType(), txtField.AccessKey, "$('#MainContent_txtField').focus(function() { $(this).select(); });", true );

Or just type the script in the HTML page suggested in the other answers.

Exel Gamboa
  • 936
  • 1
  • 14
  • 25
0

I sow this one some where , work perfectly !

            $('input').on('focus', function (e) {
                $(this)
                $(element).one('mouseup', function () {
                        $(this).select();
                        return false;
                    })                        .select();
            });
yaniv
  • 913
  • 8
  • 16
0

I'm kind of late to the party, but this works perfectly in IE11, Chrome, Firefox, without messing up mouseup (and without JQuery).

inputElement.addEventListener("focus", function (e) {
    var target = e.currentTarget;
    if (target) {
        target.select();
        target.addEventListener("mouseup", function _tempoMouseUp(event) {
            event.preventDefault();
            target.removeEventListener("mouseup", _tempoMouseUp);
        });
    }
});
-1

My solution is next:

var mouseUp;
$(document).ready(function() {
    $(inputSelector).focus(function() {
        this.select();
    }) 
    .mousedown(function () {
        if ($(this).is(":focus")) {
          mouseUp = true;
        }
        else {
          mouseUp = false;
        }
     })
     .mouseup(function () {
        return mouseUp;
     });
});

So mouseup will work usually, but will not make unselect after getting focus by input

Mari
  • 208
  • 2
  • 7