I have HTML form with a textarea
and a button
which calls the function below when a part of the text is selected. With de id of the clicked button and the selected text I want to call a php script by the POST
method.
$(document).ready(function() {
$(".postbit_buttons").on("click", ".quoted_clicked", function() {
var post = this.id;
var selected = GetSelectedText();
alert(" post = " + post + " seleted text = " + selected);
$.post("test_quoted.php", {
pid: post,
selection: selected
})
.done(function() {
alert("done")
});
});
});
Function GetSelectedText()
to get the selection was found here.
The first alert is shown with the correct information. However, after clicking OK I get the following error message on the browser console:
TypeError: 'collapse' called on an object that does not implement interface Selection.
I have used a similar construct in another part of the forum software of which this is a part, and that works.
I have pain in my eyes of staring at this, but cannot find the cause. Is there anybody who can help me on this?
@Rory The code of function GetSelectedText() is:
function GetSelectedText()
{
var selectedText=(
window.getSelection
?
window.getSelection()
:
document.getSelection
?
document.getSelection()
:
document.selection.createRange().text
);
if(!selectedText || selectedText=="")
{
if(document.activeElement.selectionStart)
{
selectedText = document.activeElement.value.substring(
document.activeElement.selectionStart
. document.activeElement.selectionEnd);
}
}
return selectedText;
}
Thanks to Rory's question I tried things out. I discovered that is was the variable "selected" in which the selected text is stored was the cause of the error. I now use the following version of GetSelectedText():
function GetSelectedText () {
if (window.getSelection) { // all browsers, except IE before version 9
var range = window.getSelection ();
return range.toString ();
}
else {
if (document.selection.createRange) { // Internet Explorer
var range = document.selection.createRange ();
return range.text;
}
}
}
and it works!! Sorry for bothering you. I do practice programming since 1968, but almost 100% was scientific computing with FORTRAN. Javascript is very new to me.
Regards, Ad Bakker