Select textarea text by clicking

Asked

Viewed 7,536 times

4

How can I do it, when I click on a certain button, the text of a given textarea or input be selected?

I wanted answers with jQuery and jQuery solutions (pure javascript).

2 answers

9


In jQuery you simply use the event select();

$('#btnSelecionar').click(function(){
$('#txtInput').select();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="4" cols="50" id="txtInput">
Testando textarea stackoverflow. 
</textarea>
<br/>
<input type="button" value="Selecionar" id="btnSelecionar"/>

In javascript you will follow the same logic. Selects the element and uses the method select() to select the text. Thus:

<textarea rows="4" cols="50" id="txtInput">
Testando textarea stackoverflow. 
</textarea>
<br/>
<button type="button" onclick="myFunction()">Selecionar</button>

<script>
function myFunction() {
    document.getElementById("txtInput").select();
}
</script>

  • 2

    +1 No kidding, @Randrade, I didn’t think it would be so easy!

  • Now, you can show an example in javascript only?

  • @Wallacemaxters Are there

  • Thanks a lot, buddy!!!

  • In Windows Phone IE press this "select" closes the browser, hahahaha #departed report bug.

  • @Renan I want at least 1% of what I win! kkk

Show 1 more comment

5

Jquery:

 $(function() {
   $(document).on('click', 'input[type=text][id=example1]', function() {
     this.select();
   });
 });

JS Puro:

document.getElementById("example2").onclick = function(){
  document.getElementById("example2").select();
}

 $(function() {
   $(document).on('click', 'input[type=text][id=example1]', function() {
     this.select();
   });
 });

document.getElementById("example2").onclick = function(){
  document.getElementById("example2").select();
}
JQuery:

<input type="text" id="example1" value="click the input to select" onclick="this.select();"/>


Js Puro:
<input type="text" id="example2" value="click the input to select" onclick="this.select();"/>

Browser other questions tagged

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