Andrew
Andrew

Reputation: 239097

How to select text in a form input when given focus?

How can you select the text in a form input when the input is given focus?

$('#my-input').on('focus', function(){
  alert('TODO: select the text');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="my-input" value="Select me on click">

Upvotes: 0

Views: 58

Answers (1)

Mouser
Mouser

Reputation: 13304

You can use HTMLInputElement.select()

$('#my-input').on('focus', function(){
  this.select();
});

$('#clickbutton').click(function(){
     $('#my-input')[0].focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="my-input" value="Select me on click">

<button id="clickbutton" value="Focus input and select" >Focus input and select</button>

Upvotes: 1

Related Questions