sunmingtao / sample-code

3 stars 4 forks source link

jQuery: how to highlight the text in an input field when clicking #302

Closed sunmingtao closed 2 years ago

sunmingtao commented 2 years ago

Naively, the code is

$(document).on('mouseup', 'input', function () {
    $(this).select();
});

The text will be briefly highlighted for a split second, then not highlighted.

It's because the default mouseup event un-highlights the text.

So the fix is to prevent the default behaviour.

$(document).on('mouseup', 'input', function (e) {
    e.preventDefault();
    $(this).select();
});