How to check if any text was selected before copying it?

Asked

Viewed 630 times

7

I have a table with several information, in local server. I use a jQuery to detect when I click on a line and pass this information via GET. On the same page, I treat this information with PHP isset().

PHP

if(isset($_GET["contrato"])){
    if($_GET["contrato"]!=""){
        $contrato = $_GET["contrato"];
        $nome = $_GET["nome"];
        $tel = $_GET["tel"];
        # Trabalho com as variáveis  
    } else {
        echo "Nenhum contato selecionado!";
    }
} else {
    echo "Nenhum contato selecionado!";
}

jQuery

$(document).ready(function(){
    $("tr[class=contato]").click(function(){
        document.execCommand("copy"); //copia o que estiver selecionado
        var msg = "?contrato="+$(this).children(".g0").html()+
                  "&nome="$(this).children(".g1").html()+
                  "&tel="$(this).children(".g2").html();
        window.location.href = msg;
    });
});

HTML

<table>
    <tr class="contato">
        <td class="g0">1000</td>
        <td class="g1">João</td>
        <td class="g2">DDD+numero</td>
    </tr>
    <tr class="contato">
        <td class="g0">1001</td>
        <td class="g1">Maria</td>
        <td class="g2">DDD+numero</td>
    </tr>
    <tr class="contato">
        <td class="g0">1002</td>
        <td class="g1">José</td>
        <td class="g2">DDD+numero</td>
    </tr>
</table>

The way it is, whenever you click on a table row, the command document.execCommand("copy"); will be executed even if there is nothing selected.

I wonder if there is any way to check, in javascript/jQuery, if the user selected something before running the command to copy.

  • 1

    $().select() only works with input or textarea see https://api.jquery.com/select/

  • So there is no way to check if any text has been selected?

  • @Paulodossantos was not I who gave the downvote, but I think you better explain what you want to do. I say this because it may be a XY problem and may have a better way to do what you want.

  • @fernandosavio I understand! But 8bit understood exactly what I wanted to say. Thank you!

2 answers

6


With the events onmouseup and onkeyup you could create a function to check whether something was selected or not.

Done this you can follow with your need (copy, change style, hide ...)

See the example below:

function algumTextoSelecionado() {
		var texto = "";
		
		if (typeof window.getSelection != "undefined")
			texto = window.getSelection().toString();
		else if (typeof document.selection != "undefined" && document.selection.type == "Text")
			texto = document.selection.createRange().text;
		
		if (texto.trim())
			alert("Texto selecionado: " + texto);
	}
	
	document.onmouseup = algumTextoSelecionado;
	document.onkeyup = algumTextoSelecionado;
<html>
	<body>	
    <div>
        <h2>Algum titulo<h2>
        <p>Texto1.1 texto1.2 texto1.3.</p>
        <p>Texto2.1 texto2.2 texto2.3.</p>
        <p>Texto3.1 texto3.2 texto3.3.</p>
    </div>
  
			<script type="text/javascript" src="master.js"></script>
	</body>
</html>

  • Thank you so much! I just didn’t understand why I received so many downvotes. :(

  • @Your question seems simple. - "Okay, you want to check if something was selected" but why ? We can help you better if you specify exactly what you need as we could probably find more than one way to find the solution to your problem. I didn’t deny your question but maybe that’s why. I’m glad to help!

  • Yes, that’s why I took "something" and put "text". But it’s not text area or text input. I don’t know how to explain it better: I just wanted that when I selected a word, it would go to the Clipboard, without giving Ctrl+C. That’s it. What I didn’t know was how to do this check you did. Thank you very much once again.

5

Whoa, whoa, whoa, whoa? To get the selected text is relatively simple. Follow the example:

function isTextSelected(input){
   var startPos = input.selectionStart;
   var endPos = input.selectionEnd;
   var doc = document.selection;

   if(doc && doc.createRange().text.length != 0){
      return true;
   }else if (!doc && input.value.substring(startPos,endPos).length != 0){
      return true;
   }
   return false;
}

$('input').click(function(){
   
   if(isTextSelected($('#textareaId')[0])){
      alert(getSelectionText());
   } 
});

function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea id="textareaId">
    teste
    teste
    teste
    teste
</textarea>
<input type="button" value="Test" />

In place of Alert, proceed with the actions you need. Hugs!

  • Thank you for answering my question! But my idea would be not to use textareas or inputs, very even a button. :/

Browser other questions tagged

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