How to Select All Text in a TextBox on focus?

Select all Text in Safari

Select all Text in Safari

Introduction

This is small tip, yet very useful when you want to select all text inside a TextBox.

Background

This was a requirement for which I researched a lot and tested on multiple browsers and devices. Let me share the problem and solution below.

Problem

When profile page is shown for a user, the password fields are also populated. The characters in a password field are masked (shown as asterisks or circles). So, typical user experience would be to select all text when you click or focus into these fields, as user can’t see the password, he/she will definitely change the whole password. Therefore, the problem is to select all the text inside the password fields.

Solution

We are going to use jQuery for this task. Solution is not so straight forward as it seems. So, the first thing comes into mind is to handle the focus event. Yes, of course, we will use that. So, the code would look like below…

$('#txtPassword').on('focus', function () {
    this.select();
});

But this is not a cross browser solution and will fail in Safari.

So, what is cross browser?

Very tricky actually. We need to specify how much text we need to select. We can specify that using the selectionStart and selectionEnd properties.

$('#txtPassword').on('focus', function () {
    this.selectionStart = 0;
    this.selectionEnd = this.value.length;
});

Now, one last thing. We need to prevent mouseup event, because that is fired automatically after focus, which deselects all the text.

$('#txtPassword').on('focus', function () {
    this.selectionStart = 0;
    this.selectionEnd = this.value.length;
});
$("#txtPassword").on('mouseup', function (e) {
    e.preventDefault();
});

Full Demo

[Demo] Select All Text in a TextBox on focus

If you have any queries, do visit my blog and drop me a Contact Tadit Dash request.

Leave a comment