mudraya katusha
mudraya katusha

Reputation: 171

how to select text with jquery using focus

I am trying to select the text inside the span element by this code but I do not succeed in it:

<span class="selectme">this text should be selected by click</span> 

$(".selectme").live('focus', function() { $(this).select(); });

This one, below, is working well:

<input value="this text should be selected by click" class="selectme">

$("input.selectme").live('focus', function() { $(this).select(); });

How can I make it work with the span element?

Upvotes: 0

Views: 49

Answers (1)

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

span doesn't works like input, so the short answer is that you can't do that. It doens't even has the focus event by default.

But there is a workaround. You need to add tabindex="-1" to make it focusable and use window.getSelection().selectAllChildren(this); to select it's value:

$(".selectme").on('focus', function() { 
    window.getSelection().selectAllChildren(this);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<span class="selectme" tabindex="-1">this text should be selected by click</span>

Source

Also live is deprecated, use on instead.

Upvotes: 2

Related Questions