Focus with selected text

Asked

Viewed 476 times

3

I have an input on I want it to have Focus and the text is already selected.

I’m doing it like this:

$(".autofocus").trigger('focus');

The problem is that the text is not selected. Does anyone know how to do this?

2 answers

4

Put this code before the Trigger code:

$(".autofocus").on("focus", function () {
   $(this).select();
});

1

The .on() is currently expendable, suffice (as documented) before the .trigger() the following code:

$(".autofocus").focus(function () {
    $(this).select();
});

You can still perform directly in the element:

<input class="autofocus" type="text" onfocus="this.select();" onmouseup="return false;" />
  • I usually use the on by default because it works even when the input is placed dynamically on the page. In fact I use up to $(Document). on("Focus", ".autofocus", Function(){}); which covers even more cases.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.