[javascript] Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

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

This question is related to javascript jquery user-interface

The answer is


_x000D_
_x000D_
<input type="text" onfocus="this.select();" onmouseup="return false;" value="test" />
_x000D_
_x000D_
_x000D_


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.


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:

    var blockMouseUp = false;
    var customerInputFocused = false;

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

        customerInputFocused = true;
      };

    txtCustomer.onblur =
      function ()
      {
        customerInputFocused = false;
      };

    txtCustomer.onmousedown =
      function ()
      {
        blockMouseUp = !customerInputFocused;
      };

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

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


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();
    });
});

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(); 
    });
});

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.


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


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


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...


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

$('input[type=text]').focus(function() {
    var _this = this;
    setTimeout(function() {
        _this.select();
    }, 10);
});

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();
    });
});

$('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.


HTML :

Enter Your Text : <input type="text" id="text-filed" value="test">

Using JS :

var textFiled = document.getElementById("text-filed");
textFiled.addEventListener("focus", function() { this.select(); });

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()}
/>

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);
        });
    }
});

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

_x000D_
_x000D_
<input type="text" onfocus="this.select();" onmouseup="return false;" value="test" />
_x000D_
_x000D_
_x000D_


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

$('input[type=text]').focus(function() {
    var _this = this;
    setTimeout(function() {
        _this.select();
    }, 10);
});

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

 $("#textBox").focus().select();

_x000D_
_x000D_
<input type="text" onfocus="this.select();" onmouseup="return false;" value="test" />
_x000D_
_x000D_
_x000D_


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.


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>

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(); 
    });
});

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.


I sow this one some where , work perfectly !

            $('input').on('focus', function (e) {
                $(this)
                $(element).one('mouseup', function () {
                        $(this).select();
                        return false;
                    })                        .select();
            });

onclick="this.focus();this.select()"

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:

    var blockMouseUp = false;
    var customerInputFocused = false;

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

        customerInputFocused = true;
      };

    txtCustomer.onblur =
      function ()
      {
        customerInputFocused = false;
      };

    txtCustomer.onmousedown =
      function ()
      {
        blockMouseUp = !customerInputFocused;
      };

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

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


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


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.


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.


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.)


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


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...


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.)


onclick="this.focus();this.select()"

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

$('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.


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.


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

 $("#textBox").focus().select();

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


$(document).ready(function() {
    $("input:text")
        .focus(function () { $(this).select(); } )
        .mouseup(function (e) {e.preventDefault(); });
});

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.


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);
        });
    }
});

I sow this one some where , work perfectly !

            $('input').on('focus', function (e) {
                $(this)
                $(element).one('mouseup', function () {
                        $(this).select();
                        return false;
                    })                        .select();
            });

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>

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


$(document).ready(function() {
    $("input:text")
        .focus(function () { $(this).select(); } )
        .mouseup(function (e) {e.preventDefault(); });
});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to user-interface

Calling another method java GUI How do I center text vertically and horizontally in Flutter? Is it possible to put a ConstraintLayout inside a ScrollView? How to change color of the back arrow in the new material theme? How to create RecyclerView with multiple view type? Android RecyclerView addition & removal of items tkinter: how to use after method Presenting a UIAlertController properly on an iPad using iOS 8 Android ViewPager with bottom dots How do I get the height and width of the Android Navigation Bar programmatically?