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

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?

Solutions/Answers:

Solution 1:

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

Solution 2:

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

Solution 3:

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

Solution 4:

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

Solution 5:

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.

Solution 6:

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>

From CSS Trics.