Advertisement
Advertisement


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


Question

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

2017/11/11
1
312
11/11/2017 3:08:26 PM

Accepted Answer

$(document).ready(function() {
    $("input:text").focus(function() { $(this).select(); } );
});
2011/07/15
369
7/15/2011 6:06:34 PM


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

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

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

2020/01/27

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.

2013/02/06

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 inside render function -

<input
  type="text"
  value="test"
  onFocus={e => e.target.select()}
/>
2020/01/09

Source: https://stackoverflow.com/questions/480735
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]