I am trying to get the user selected text in a text input when a button is clicked. This what I am trying:
<head>
<script type="text/javascript">
function GetSelectedText () {
if (window.getSelection) { // all browsers, except IE before version 9
var range = window.getSelection ();
alert (range.toString ());
}
else {
if (document.selection.createRange) { // Internet Explorer
document.getElementById("foo").focus();
var range = document.selection.createRange();
alert (range.text);
}
}
}
</script>
</head>
<body>
<button onclick="GetSelectedText ()">Get the selected text!</button>
<input type = 'text' id = 'foo' />12345
</body>
It works as expected in all browsers, except IE9
. In IE9
, if you select some text from the 12345
chunk and press the button, the selected text is alerted all right. However, if you type something in the text input, select some of it, and click the button, a blank alert is generated.
Can anyone tell me how do I get it working in IE9
? And is there any way to get the cursor position of the selection start as well (something like Mozilla's selectionStart
)? Iam looking for Javascript solution, without Rangy
or other related jQuery libraries..