HTML code--
<script language="javascript" type="text/javascript" src="开发者_如何学Pythonjs/jquery-1.4.2.min.js"></script>
<script language="javascript" type="text/javascript" src="js/jquery.field.selection.js"></script>
<div id="copy">Copy</div>
<textarea....id="t">
jquery---
$(docu.....
$('#copy').click(function(){
var range = $('#TextArea').getSelection();
alert(range.text);
});
});
When the #copy button is pressed the alert does not show the selected text in #t. It comes in blank.
I need the selected text from the textarea
Your code is not running because, this statement fails
var range = $('#TextArea').getSelection();
There is nothing as TextArea
as ID in the markup you provided, so the script encounters an error and does not continue beyond it.
If you place the alert at the top part, I am sure the alert box will pop up. i.e
$('#copy').click(function(){
alert(''); //this will work
var range = $('#TextArea').getSelection();
alert(range.text);
});
getSelection
is a method of the document, so you should do:
var range = document.getSelection();
also note that you'll have to use document.selection.createRange()
in IE so everything gets a bit complicated.
take a look at this example for more information. you'll end up needing a function like this:
function getSelectedText(){
if(document.all){
var selection = document.selection;
var newRng = selection.createRange();
newRng.select();
return newRng.htmlText;
}else{
return document.getSelection();
}
}
wich should return the selected text and work in all major browsers.
EDIT:
just saw you're using some kind of jquery-plugin that (maybe) should make your code work. the problem is:
in your html, the id of the textarea is "t":
<textarea....id="t">
but in your javascript, you're trying to get the selection of id "TextArea":
$('#TextArea').getSelection();
please change the id of your textarea to "TextArea" (or the other way around) and see what happens.
I'm not sure about the question, but if you need to get the textarea value, just use the val
jQuery method:
http://api.jquery.com/val/
$('#copy').click(function(){
var range = $('#t').val();
alert(range);
});
Either you change your id="t"
or you change #TextArea
to #t
to get the textarea you have in your html markup.
But I have no idea what plugin that you are using or what it want.
精彩评论