jQuery select text in text input on focus


$(function () {
    $('input.target1').focus(function () { // select text on focus
    $('input.target1').mouseup(function (e) { // fix for chrome and safari
    $('input.target2').select(function () {
        $('.log').append(' Handler for .select() called. ');


<form class="well">
        <input type="text" class="form-control target1" value="click or focus this input to select text in it">
        <input type="text" class="form-control target2" value="try to select text in this input">
    <div class="log"></div>

3 thoughts on “jQuery select text in text input on focus”

  1. This is a cool solution, but by always preventing the default action on mouseup events, you prevent organic selection from occurring after the focus event has passed. One way to avoid this is to wrap the mousup listener inside the focus listener and turn it off as soon as it's been processed. Also, you can listen to the keyup event and turn off the handler, in case someone tabs into the field so you don't perform the selection twice.

    Here's some more explanation and code from my stack overflow answer here:

    Here's a demo in jsFiddle:

    Here's a code snippet to use:
    $(this).on("mouseup.a keyup.a", function(e){
    $(this).off("mouseup.a keyup.a").select();


Leave a Comment