Select text from textarea when clicking

3

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

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

    
asked by anonymous 16.10.2015 / 14:11

2 answers

7

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><textarearows="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 select () method to select the text. Staying like this:

<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>
    
16.10.2015 / 14:21
4

Jquery:

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

JS Pure:

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();"/>
    
16.10.2015 / 14:27