jQuery select text in text input on focus

js:

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

html:

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

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:
    http://stackoverflow.com/a/24578197/1366033

    Here's a demo in jsFiddle:
    http://jsfiddle.net/KyleMit/ccf7S/

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

    Reply

Leave a Reply to Koi Cancel reply