I have a simple HTML page where I want the selected text inside text area to use it for some processing. I have written jQuery code but I am always getting empty string as selection. Please help me to fix this issue in my code.
HTML code is as given below:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" />
</head>
<body>
<form action="#" id="formfirst">
<textarea name="tafirst" rows="10" id="tafirst">Along came Polly ---- Reality Bites ---- Duplex ---- Walter Mitty </textarea>
<br>
<input type="text" id="txtfirst">
<br>
<input type="submit">
</form>
</body>
<script type="text/javascript" src="js/verify.js"></script>
</html>
Javascript code is given below:(verify.js)
function getSelectedText(){
var t = '';
if(window.getSelection){
t = window.getSelection();
}else if(document.getSelection){
t = document.getSelection();
}else if(document.selection){
t = document.selection.createRange().text;
}
return t;
}
$(document).ready(function(){
//alert("HERE 1");
});
$(document).keypress(function(e){
if($('#tafirst').is(':focus')){
if(e.altKey && e.which==97){
alert(getSelectedText());
e.preventDefault();
}
}
});
EDIT
I have downloaded rangy plugin and put it inside my js folder. I have included that plugin in my HTML as given below:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="js/rangy/rangy-1.2.3/rangy-core.js"></script>
</head>
<body>
<form action="#" id="formfirst">
<textarea name="tafirst" rows="10" id="tafirst">Along came Polly ---- Reality Bites ---- Duplex ---- Walter Mitty </textarea>
<br>
<input type="text" id="txtfirst">
<br>
<input type="submit">
</form>
</body>
<script type="text/javascript" src="js/verify.js"></script>
</html>
Corresponding modified js file is as follows:
var range = rangy.createRange();
$(document).ready(function(){
alert(range);
alert("HERE 1");
});
$(document).keypress(function(e){
if($('#tafirst').is(':focus')){
if(e.altKey && e.which==97){
alert(getSelectedText());
e.preventDefault();
}
}
});
But it is not even showing any alert message. Have I done anything wrong while adding rangy's js reference?