685

I have the following code to display a textbox in a HTML webpage.

<input type="text" id="userid" name="userid" value="Please enter the user ID" />

When the page displays, the text contains the Please enter the user ID message. However, I found that the user needs to click 3 times in order to select all the text (in this case it is Please enter the user ID).

Is it possible to select the entire text with only one click?

Edit:

Sorry, I forgot to say: I must use the input type="text"

Oscar Mederos
  • 29,016
  • 22
  • 84
  • 124
Questions
  • 20,055
  • 29
  • 72
  • 101
  • 6
    A better approach is to use a ` – Quentin Nov 01 '10 at 08:34
  • 13
    Or even use a placeholder if you're working in a modern, HTML5 project. – Léo Lam Oct 26 '14 at 11:17
  • 1
    placeholder="Please enter the user ID" – Marcelo Bonus Aug 15 '19 at 19:14
  • 2
    Easy with CSS: `input { user-select: all; }` – Avatar Feb 05 '23 at 06:50
  • This question has options for when .select() is not working on mobile platforms: https://stackoverflow.com/questions/3272089/programmatically-selecting-text-in-an-input-field-on-ios-devices-mobile-safari – Dean Radcliffe Dec 02 '13 at 04:47

29 Answers29

1130

You can use the JavaScript .select() method for HTMLElement:

<label for="userid">User ID</label>
<input onClick="this.select();" value="Please enter the user ID" id="userid" />

But apparently it doesn't work on mobile Safari. In those cases you can use:

<input onClick="this.setSelectionRange(0, this.value.length)" value="Sample Text" id="userid" />
Andy
  • 4,783
  • 2
  • 26
  • 51
Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148
  • 9
    To make that more general, you could use `this.id` as the argument for the click handler. Better yet, you could eliminate the `getElementById` entirely and pass `this` as an argument. – Asad Saeeduddin Dec 14 '12 at 23:05
  • 13
    On mobile Safari that doesn't work. Try calling this.setSelectionRange(0, 9999) instead. – Dean Radcliffe Dec 02 '13 at 04:44
  • 53
    @DeanRadcliffe Nice one! I'd use `this.setSelectionRange(0, this.value.length)` instead. – cvsguimaraes Mar 10 '14 at 05:59
  • 12
    [Why Should I Avoid Inline Scripting?](http://programmers.stackexchange.com/questions/86589/why-should-i-avoid-inline-scripting) – Iulian Onofrei Apr 20 '15 at 06:53
  • 3
    But what if the input type is number? – fung Jul 05 '16 at 03:37
  • 9
    Any updates on browser support? https://www.w3schools.com/jsref/met_text_select.asp claims it is supported by all browsers – Ayyash Apr 24 '17 at 05:05
  • 1
    To improve this answer you should add @LenArt bit about using `readonly` instead of `disabled="disabled"` if you want this to work with a non-editable field. – Codemonkey Oct 04 '18 at 08:23
  • 1
    A simple addition for being able to place curser after select somewhere, I added a script in head with `var inp_sel = false;` and changed the event to `onfocus="if(!inp_sel) { inp_sel=true; this.select(); } else { inp_sel=false; }" onmouseout="inp_sel=false;"` – bobble bubble Jan 19 '19 at 13:47
  • Most always you will want to edit things like bobble bubble says - just change the onClick to onFocus and simplify the whole thing – Devin McQueeney Apr 13 '19 at 15:36
  • 1
    `onClick="select()"` will also work. In Chrome, even `onClick="select"` is enough. This doesnt work in Firefox though. Apart from that, `this.focus()` would probably be preferred instead of `click` so it works when using tab or assistive technology, too. – phil294 Nov 20 '19 at 11:25
  • @phil294 The default is for text to be selected on focus (like if you tab to an input), so that really doesn't add anything... – mbomb007 Dec 20 '19 at 15:04
  • @mbomb007 huh, right, it doesnt matter for accessiblity then. Guess it still makes more sense to use `focus` as it also handles programmatic focus / is more generic in general. – phil294 Dec 20 '19 at 17:42
  • 3
    `onfocus` is probably a better choice than `onclick`. With `onfocus` it will only select everything when you first click in the box. With `onclick` it will select everything everytime you click somewhere in the box, even if you are already in the box. – jsherk Jan 24 '20 at 03:27
  • FYI, the selection range version doesn't work for a number type input – kthornbloom Feb 27 '20 at 13:42
91

The previously posted solutions have two quirks:

  1. In Chrome the selection via .select() doesn't stick - adding a slight timeout resolves this issue.
  2. It's impossible to place the cursor at a desired point after focus.

Here's a complete solution that selects all text on focus, but allows selecting a specific cursor point after focus.

$(function () {
    var focusedElement;
    $(document).on('focus', 'input', function () {
        if (focusedElement == this) return; //already focused, return so user can now place cursor at specific point in input.
        focusedElement = this;
        setTimeout(function () { focusedElement.select(); }, 100); //select all text in any field on focus for easy re-entry. Delay sightly to allow focus to "stick" before selecting.
    });
});
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
Cory House
  • 14,235
  • 13
  • 70
  • 87
  • 9
    To handle the case where the user clicks away from the field then back again, add `.on('blur', 'input', function(){focusedElement = null;})` – Tamlyn Feb 25 '14 at 14:12
  • 2
    a timeout of `0` works for me in chrome and firefox. not sure where your timeout of `50` is coming from. – thejoshwolfe Aug 04 '15 at 02:12
  • 1
    The solution is to use onClick instead onFocus. Works perfectly and does not need complicated codes. – Ismael Aug 08 '15 at 23:49
  • @Ismael - onClick wouldn't fire when the input is focused via tabbing. – Cory House Aug 10 '15 at 13:59
  • 5
    @CoryHouse it does not matter, because Focus via tab natively select the text! No javascript required. – Ismael Aug 11 '15 at 14:40
  • The timeout mentioned here works well in conjunction with `document.execCommand()`, mentioned in @Toastrackenigma answer. – Eric Lease Jan 27 '17 at 07:16
  • I am not a fan of using setTimeout, but this was the only way I managed to select all text on a READ-ONLY text input in Safari / iOS 11 – Tiago Nov 07 '17 at 17:52
  • 1
    @CoryHouse even after 4 years your codes works like a charm. Man, Take a bow. Thanks for this little dirty hack. I was searching for 2-3 days until I found this one. :+1: – Rutvij Kothari Dec 06 '17 at 07:36
  • This code is not reliable, please try to mouse down and wait 1 second, you will see that selection was forced by browser anyway. – puchu Jan 14 '20 at 10:53
  • Why is it not possible to place cursor after focus? If the text is already selected, the focus event is not called on the next click. – chetan Oct 25 '21 at 06:44
55

Html (you'll have to put the onclick attribute on every input you want it to work for on the page)

 <input type="text" value="click the input to select" onclick="this.select();"/>

OR A BETTER OPTION

jQuery (this will work for every text input on the page, no need to change your html):

<script  type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>  
<script type="text/javascript">
    $(function(){
        $(document).on('click','input[type=text]',function(){ this.select(); });
    });
</script>
oLinkWebDevelopment
  • 1,841
  • 15
  • 8
  • 25
    Would probably be better to bind to the focus event rather than click for those who tab through the form elements. – Andrew Ensley Dec 10 '12 at 15:29
  • 8
    @Andrew That's not necessary as the text is always selected if you tab through input elements. ;-) – nietonfir Oct 28 '13 at 15:40
  • focus events are glitchy, the blur event on the other hand comes in handy for triggering validation and auto-saving of forms, works when you tab through too! – oLinkWebDevelopment Mar 08 '14 at 20:05
  • Should work fine, make sure you are using an updated version of jQuery, or use $(document).live() on older versions. – oLinkWebDevelopment Aug 08 '14 at 18:11
  • 2
    Unless the user already has jQuery a better option does not involve adding a dependency on a third party library. – Ross Jan 13 '16 at 01:27
  • As one who tries to avoid coding event handlers in the HTML, this was the perfect solution. I can't imagine why it doesn't have more up-votes. – Ixalmida Mar 14 '16 at 19:46
43

You should not use this approach to provide examples for input values (any more).

The best option is to now use the placeholder HTML attribute if possible:

<label for="userid">User ID</label>
<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />

This will cause the text to show unless a value is entered, eliminating the need to select text or clear inputs.

Beware that placeholders are no replacement for labels, as they disappear once text is entered, and pose issues for accessibility.

Andy
  • 4,783
  • 2
  • 26
  • 51
Thom Porter
  • 2,604
  • 2
  • 19
  • 23
20

You can always use document.execCommand (supported in all major browsers)

document.execCommand("selectall", null, false);

Selects all text in the currently focused element.


Update 2021: execCommand is now deprecated.

It's probably for the best to be honest, as it was an old IE API which had been adopted by the other browsers, and it was always a little weird to work with. Nevertheless, it was nice to have one solution which worked both with <input> fields and contenteditable elements.

.select() is probably the best way to go for <input> fields these days.

For contenteditable, the modern solution there is to use the range API.

Toastrackenigma
  • 7,604
  • 4
  • 45
  • 55
  • 1
    This looks to be an elegant solution. The complete code would look like: `` – pipepiper Dec 26 '16 at 10:07
  • Yeah, it's my favourite way to do this kind of task, esp. as it works for `contenteditable` elements as well. I think you can also make it even slightly more elegant, i.e. `` - pretty sure you can remove the `null` and `false` if you don't use them. – Toastrackenigma Dec 28 '16 at 03:16
  • Yeah. `onfocus` seems better than `onclick`. and yes, one can do away with `null` and `false`. Thanks! – pipepiper Dec 28 '16 at 11:05
  • I would agree that this is the best cross-browser solution with the caveat that the timeout mentioned in @Corey House solution should be used to make this cross browser compatible. – Eric Lease Jan 27 '17 at 07:17
  • 2
    when using `onfocus`, the whole page is selected when input is clicked in Chrome. `onclick` works fine. – robotik May 16 '17 at 23:18
  • Before execute focus after use select all.. thanks a link caiuse.com – KingRider Dec 18 '19 at 11:31
  • 1
    MDN says `execCommand` is now [deprecated](https://developer.mozilla.org/en-US/docs/Web/API/document/execCommand). – arcanemachine Jun 08 '21 at 03:58
  • 1
    @arcanemachine Cheers, thanks for letting me know. I've added a notice to the post :) – Toastrackenigma Jun 08 '21 at 04:06
  • FYI, `contenteditable` could go very wrong in some scenarios. If scenario is basic, you should get away with just `contenteditable` Can learn more from ReactJS talk why FB created DraftJs. https://www.youtube.com/watch?v=feUYwoLhE_4 – Lukas Liesis Dec 17 '21 at 07:44
16

Note: When you consider onclick="this.select()", At the first click, All characters will be selected, After that maybe you wanted to edit something in input and click among characters again but it will select all characters again. To fix this problem you should use onfocus instead of onclick.

Amir Fo
  • 5,163
  • 1
  • 43
  • 51
13

Try:

onclick="this.select()"

It works great for me.

Stephen
  • 576
  • 8
  • 19
13

The answers listed are partial according to me. I have linked below two examples of how to do this in Angular and with JQuery.

This solution has the following features:

  • Works for all browsers that support JQuery, Safari, Chrome, IE, Firefox, etc.
  • Works for Phonegap/Cordova: Android and IOs.
  • Only selects all once after input gets focus until next blur and then focus
  • Multiple inputs can be used and it does not glitch out.
  • Angular directive has great re-usage simply add directive select-all-on-click
  • JQuery can be modified easily

JQuery: http://plnkr.co/edit/VZ0o2FJQHTmOMfSPRqpH?p=preview

$("input").blur(function() {
  if ($(this).attr("data-selected-all")) {
  //Remove atribute to allow select all again on focus        
  $(this).removeAttr("data-selected-all");
  }
});

$("input").click(function() {
  if (!$(this).attr("data-selected-all")) {
    try {
      $(this).selectionStart = 0;
      $(this).selectionEnd = $(this).value.length + 1;
      //add atribute allowing normal selecting post focus
      $(this).attr("data-selected-all", true);
    } catch (err) {
      $(this).select();
      //add atribute allowing normal selecting post focus
      $(this).attr("data-selected-all", true);
    }
  }
});

Angular: http://plnkr.co/edit/llcyAf?p=preview

var app = angular.module('app', []);
//add select-all-on-click to any input to use directive
app.directive('selectAllOnClick', [function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var hasSelectedAll = false;
      element.on('click', function($event) {
        if (!hasSelectedAll) {
          try {
            //iOS, Safari, thows exception on Chrome etc
            this.selectionStart = 0;
            this.selectionEnd = this.value.length + 1;
            hasSelectedAll = true;
          } catch (err) {
            //Non iOS option if not supported, e.g. Chrome
            this.select();
            hasSelectedAll = true;
          }
        }
      });
      //On blur reset hasSelectedAll to allow full select
      element.on('blur', function($event) {
        hasSelectedAll = false;
      });
    }
  };
}]);
D Prinsloo
  • 346
  • 2
  • 6
  • nice angularjs solution. thx. although I don't use the hasSelectedAll flag. I guess this a provision for a second click which might mean the user wants to place the cursor. – dewd Oct 19 '17 at 13:18
11

input autofocus, with onfocus event:

<INPUT onfocus="this.select();" TYPE="TEXT" NAME="thing" autofocus>

This lets you open a form with the desired element selected. It works by using autofocus to hit the input, which then sends itself an onfocus event, which in turn selects the text.

fyngyrz
  • 2,458
  • 2
  • 36
  • 43
11

I was looking for a CSS-only solution and found this works for iOS browsers (tested safari and chrome).

It does not have the same behavior on desktop chrome, but the pain of selecting is not as great there because you have a lot more options as a user (double-click, ctrl-a, etc):

.select-all-on-touch {
    -webkit-user-select: all;
    user-select: all;
}
Nathan Hanna
  • 4,643
  • 3
  • 28
  • 32
6

Indeed, use onclick="this.select();" but remember not to combine it with disabled="disabled" - it will not work then and you will need to manually select or multi-click to select, still. If you wish to lock the content value to be selected, combine with the attribute readonly.

LenArt
  • 333
  • 3
  • 6
6

You can replace

<input type="text" id="userid" name="userid" value="Please enter the user ID" />

With:

<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />

The placeholder is used to replace value as how you wanted people to be able to Type in the text box without having to click multiple times or using ctrl + a. Placeholder makes it so it isn't a value but as the name suggests a place holder. That is what is used in multiple online forms that says "Username here" or "Email" and when you click on it the "Email" disappears and you can start typing right away.

Pablo
  • 71
  • 1
  • 3
5

I think its better to control via event. This variant looks pretty intuitively and work with ts as well:

    onFocus={e => {
      e.target.select();
    }

If you need selectAll every click then you can use this:

    onClick={e => {
      e.target.focus();
      e.target.select();
    }
  • I get the right click context menu appearing when I follow your suggestion in angular – Kieran Ryan Jan 27 '22 at 18:57
  • This does not work on the second click. There has to be setTimeout(() => e.target.select(), 0) to select all the time – Dawe Mar 02 '22 at 09:42
4

Here's a reusable version of Shoban's answer:

<input type="text" id="userid" name="userid"
 value="Please enter the user ID" onfocus="Clear(this);"
/>

function Clear(elem)
{
elem.value='';
}

That way you can reuse the clear script for multiple elements.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
4

Here's an example in React, but it can be translated to jQuery on vanilla JS if you prefer:

class Num extends React.Component {

    click = ev => {
        const el = ev.currentTarget;
        if(document.activeElement !== el) {
            setTimeout(() => {
                el.select();    
            }, 0);
        }
    }

    render() {
        return <input type="number" min={0} step={15} onMouseDown={this.click} {...this.props} />
    }
}

The trick here is to use onMouseDown because the element has already received focus by the time the "click" event fires (and thus the activeElement check will fail).

The activeElement check is necessary so that they user can position their cursor where they want without constantly re-selecting the entire input.

The timeout is necessary because otherwise the text will be selected and then instantly unselected, as I guess the browser does the cursor-positioning check afterwords.

And lastly, the el = ev.currentTarget is necessary in React because React re-uses event objects and you'll lose the synthetic event by the time the setTimeout fires.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
3

The exact solution to what you asked is :

<input type="text" id="userid" name="userid" value="Please enter the user ID" onClick="this.setSelectionRange(0, this.value.length)"/>

But I suppose,you are trying to show "Please enter the user ID" as a placeholder or hint in the input. So,you can use the following as a more efficient solution:

<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
Ayan
  • 8,192
  • 4
  • 46
  • 51
3

<label for="userid">User ID</label>
<input onClick="this.select();" value="Please enter the user ID" id="userid" />
Kriss Yu
  • 31
  • 1
  • Answer needs supporting information Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](https://stackoverflow.com/help/how-to-answer). – moken Apr 07 '23 at 01:54
2

The problem with catching the click event is that each subsequent click within the text will select it again, whereas the user was probably expecting to reposition the cursor.

What worked for me was declaring a variable, selectSearchTextOnClick, and setting it to true by default. The click handler checks that the variable's still true: if it is, it sets it to false and performs the select(). I then have a blur event handler which sets it back to true.

Results so far seem like the behavior I'd expect.

(Edit: I neglected to say that I'd tried catching the focus event as someone suggested,but that doesn't work: after the focus event fires, the click event can fire, immediately deselecting the text).

Luxocrates
  • 221
  • 2
  • 4
2

Html like this <input type="text" value="click the input to select" onclick="javascript:textSelector(this)"/>

and javascript code without bind

function textSelector(ele){
    $(ele).select();
}
1

Use "placeholder" instead of "value" in your input field.

seaJay
  • 37
  • 1
1

Well this is normal activity for a TextBox.

Click 1 - Set focus

Click 2/3 (double click) - Select text

You could set focus on the TextBox when the page first loads to reduce the "select" to a single double-click event.

RPM1984
  • 72,246
  • 58
  • 225
  • 350
1

Use this:

var textInput = document.querySelector("input");
textInput.onclick = function() {
  
  textInput.selectionStart = 0;
  textInput.selectionEnd = textInput.value.length;

}
<input type="text">
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Coder_Naveed
  • 526
  • 5
  • 5
1

I'm using the focus-attribute in my vue application

<input @focus="$event.target.select()" />
wittgenstein
  • 3,670
  • 7
  • 24
  • 41
0

If you are using AngularJS, you can use a custom directive for easy access:

define(['angular'], function () {
    angular.module("selectionHelper", [])
    .directive('selectOnClick', function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {                
                element.on('click', function () {
                    this.select();
                });
            }
        };
    });
});

Now one can just use it like this:

<input type="text" select-on-click ... />

The sample is with requirejs - so the first and the last line can be skipped if using something else.

timtos
  • 2,225
  • 2
  • 27
  • 39
0

If anyone want to do this on page load w/ jQuery (sweet for search fields) here is my solution

jQuery.fn.focusAndSelect = function() {
    return this.each(function() {
        $(this).focus();
        if (this.setSelectionRange) {
            var len = $(this).val().length * 2;
            this.setSelectionRange(0, len);
        } else {
            $(this).val($(this).val());
        }
        this.scrollTop = 999999;
    });
};

(function ($) {
    $('#input').focusAndSelect();
})(jQuery);

Based on this post . Thanks to CSS-Tricks.com

Hugo Dias
  • 169
  • 3
  • 14
0

If you are just trying to have placeholder text that gets replaced when a user selects the element then it is obviously best practice to use placeholder attribute nowadays. However, if you want to select all of the current value when a field gains focus then a combination of @Cory House and @Toastrackenigma answers seems to be most canonical. Use focus and focusout events, with handlers that set/release the current focus element, and select all when focused. An angular2/typescript example is as follows (but would be trivial to convert to vanilla js):

Template:

<input type="text" (focus)="focus()" (focusout)="focusout()" ... >

Component:

private focused = false;

public focusout = (): void => {
    this.focused = false;
};

public focus = (): void => {
    if(this.focused) return;
    this.focused = true;

    // Timeout for cross browser compatibility (Chrome)
    setTimeout(() => { document.execCommand('selectall', null, false); });
};
Eric Lease
  • 4,114
  • 1
  • 29
  • 45
0

If you are looking for a pure vanilla javascript method, you can also use:

document.createRange().selectNodeContents( element );

This will select all the text and is supported by all major browsers.

To trigger the selection on focus, you just need to add the event listener like so:

document.querySelector( element ).addEventListener( 'focusin', function () {

    document.createRange().selectNodeContents( this );

} );

If you want to place it inline in your HTML, then you can do this:

<input type="text" name="myElement" onFocus="document.createRange().selectNodeContents(this)'" value="Some text to select" />

This is just another option. There appears to be a few ways of doing this. (document.execCommand("selectall") as mentioned here as well)

document.querySelector('#myElement1').addEventListener('focusin', function() {

  document.createRange().selectNodeContents(this);

});
<p>Cicking inside field will not trigger the selection, but tabbing into the fields will.</p>
<label for="">JS File Example<label><br>
<input id="myElement1" value="This is some text" /><br>
<br>
<label for="">Inline example</label><br>
<input id="myElement2" value="This also is some text" onfocus="document.createRange().selectNodeContents( this );" />
stldoug
  • 853
  • 9
  • 14
0

Using placeholder="Please enter the user ID" instead of value="Please enter the user ID" is the best approach for this scenario, but the function can be useful in some cases.

<input> elements can already listen to focus event. We can just add the event listener to it instead of document, and there is no further needs to listen to click.

Plain JavaScript:

document.getElementById("userid").addEventListener("focus", function() {
    this.select();
});

With JQuery:

$("#userid").on("focus", function() {
    this.select();
});

You may use this.setSelectionRange(0, this.value.length) instead of this.select() depends on your purpose but that will not work on some input types such as number.

Quicksilver
  • 136
  • 8
0

Live demo

<input id="my_input" style="width: 400px; height: 30px;" value="some text to select">
<br>
<button id="select-bn" style="width: 100px; height: 30px; margin-top: 20px;cursor:pointer;">Select all</button>
<br><br>
OR 
<br><br>
Click to copy
<br><br>
<input id="my_input_copy" style="width: 400px; height: 30px;" value="some text to select and copy">
<br>
<button id="select-bn-copy" style="width: 170px; height: 30px; margin-top: 20px;cursor:pointer;">Click copy text</button>


<script type="text/javascript">
$(document).on('click', '#select-bn', function() {
  $("#my_input").select();
});


//click to select and copy to clipboard

var text_copy_bn = document.getElementById("select-bn-copy");
text_copy_bn.addEventListener('click', function(event) {
  var copy_text = document.getElementById("my_input_copy");
  copy_text.focus();
  copy_text.select();
  try {
    var works = document.execCommand('copy');
    var msg = works ? 'Text copied!' : 'Could not copy!';
    alert(msg);
  } catch (err) {
    alert('Sorry, could not copy');
  }
});
</script>
Dexter
  • 74
  • 8