Reputation: 33685
How do I get javascript or jquery to grab me text that I've selected/high lighted with my mouse or keyboard?
Upvotes: 0
Views: 884
Reputation: 2810
Similar to the above, this outputs the selected text to a div (adapted from http://mark.koli.ch/2009/09/use-javascript-and-jquery-to-get-user-selected-text.html):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script language=javascript>
$(document).ready( function() {
var txt = '';
function getSelected()
{
if (window.getSelection) {
txt = window.getSelection();
}
else if(document.getSelection) {
txt = document.getSelection();
}
else if(document.selection) {
txt = document.selection.createRange().text;
}
txt = txt.toString();
return txt;
}
$('#container').mouseup( function() {
$('#message').html(getSelected());
});
});
</script>
<style type="text/css">
#message {
min-height: 20px;
width: 300px;
border: 1px solid orange;
padding: 5px;
}
</style>
<div id="message"></div>
<div id="container">
<p>Text to select</p>
</div>
Upvotes: 1
Reputation: 30002
For textareas, you can use this (as seen on javascript wrap text with tag ):
var val;
el = document.getElementById('textarea');
if (el.setSelectionRange) {
//webkit & ff
var val = el.value.substring(el.selectionStart,el.selectionEnd);
}
else if(document.selection.createRange()) {
// ie
var val = document.selection.createRange().text;
}
Upvotes: 0