1

Possible Duplicate:
Understanding what goes on with textarea selection with JavaScript
Copy and paste the selected text to the clipboard using JavaScript

I'm a little confused about how i should approach this, i have a textbox in this area i want a user to be able to highlight a word in textbox. I need to capture the highlighted word. It works in all browsers except Mozilla.

Here Im using onkeydown event.

var startPos = textComponent.selectionStart;        
var endPos = textComponent.selectionEnd;

selected = textComponent.value.substring(startPos,endPos);

This is a code i used it for Mozilla. It is not working.

Please help me

Community
  • 1
  • 1
Suga24
  • 55
  • 1
  • 7
  • That code works in Mozilla browsers, so long as the selection actually exists. When are you calling this code? It's almost certain that the selection doesn't exist by the time the code is called. – Tim Down Jul 13 '12 at 11:00

2 Answers2

0

Used google a bit and found this: http://www.codeproject.com/Articles/292159/Javascript-code-to-get-selected-text Not sure if works, but maybe helps :)

Kristian
  • 3,283
  • 3
  • 28
  • 52
0
Howvever, I managed to fix this by this code. Please use this below coding for capturing the textbox selected value.

<**head>
    <script type="text/javascript">
        function GetSelectedText () {
            var selText = "";
            if (window.getSelection) {  // all browsers, except IE before version 9
                if (document.activeElement && 
                        (document.activeElement.tagName.toLowerCase () == "textarea" || 
                         document.activeElement.tagName.toLowerCase () == "input")) 
                {
                    var text = document.activeElement.value;
                    selText = text.substring (document.activeElement.selectionStart, 
                                              document.activeElement.selectionEnd);
                }
                else {
                    var selRange = window.getSelection ();
                    selText = selRange.toString ();
                }
            }
            else {
                if (document.selection.createRange) { // Internet Explorer
                    var range = document.selection.createRange ();
                    selText = range.text;
                }
            }
            if (selText !== "") {
                alert (selText);
            }
        }
    </script>
</head>
<body onmouseup="GetSelectedText ()">
    Some text for selection.
    <br /><br />
    <textarea>Some text in a textarea element.</textarea>
    <input type="text" value="Some text in an input field." size="40"/>
    <br /><br />
    Select some content on this page!
</body>**
Suga24
  • 55
  • 1
  • 7