Serjas
Serjas

Reputation: 2284

get highlighted text using jquery .select()?

I was trying example code found here http://api.jquery.com/select/

$(":input").select( function () { 
      $("div").text("Something was selected").show().fadeOut(1000); 
    });

Now my question is instead of printing "Something was selected" , can I get exact selected text?

I want jquery .select() specific answers . I got other solution from here

Upvotes: 8

Views: 15830

Answers (3)

Rojen George
Rojen George

Reputation: 11

 <script>
window.onmouseup = mouseup;
function mouseup() {
 getSelText();
 }
</script>
   <script  type="text/javascript">
function getSelText() {
var txt = '';
if (window.getSelection) {
    alert (window.getSelection());
} else if (document.getSelection) {
   alert (document.getSelection());
   } else if (document.selection) {
     alert( document.selection.createRange().text);

 } else return;

 }
</script>  

Upvotes: 0

Ellipsis
Ellipsis

Reputation: 117

.Select() seems like just an event that will fire on selection of that specific element. However, to get the text you will need to use javascript's window.getSelection() function.

Here is an example: http://jsfiddle.net/BCv4Y/3/

    $(":input").select( function () { // on selection, show what's selected
        $("div").text(window.getSelection()).show().fadeOut(1000); 
     }

});

Perhaps, It will be great if new version of jquery comes with something like $(this).selectedVal(). Hope that helps

Upvotes: 5

ithcy
ithcy

Reputation: 5589

.select() has nothing to do with retrieving the actual selected text. Select is just like .click(): an easy, shorthand way way to bind a handler function to the select event.

It says right in the API docs:

The method for retrieving the current selected text differs from one browser to another. A number of jQuery plug-ins offer cross-platform solutions.

So you bind with element.select(...) (or better still, element.on("select", ...)), and then you use one of the many cross-platform solutions to retrieve the selection. This is the basic idea: http://jsfiddle.net/NjW5a/3/

Upvotes: 10

Related Questions