Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Retrieving the text contents and reading the selected portion of a field's value

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 117
    Comment on it

    To retrieve the text selected by the user is to get the indices of the starting and the ending character of the selection. After that you need to extract that particular portion from the form fields value using those retrieved values.

    To get the indices of the current active selection, we use two methods. These are :-

    1.formElement.selectionStart: This will return the first character of the selected text. If no text is selected, this contains the index of the character that follows the input cursor.

    2.formElement.selectionEnd: This will return the last character of the selected text. If no text is selected, this contains the index of the character that follows the input cursor.

    Here is an example of their usage:

    <html>
    <textarea id=sampleText  cols="50" rows="5">
        ..Some text here
        </textarea>
    
        <div id=result></div>
    
        <script>
    
        var sampleTextarea = document.getElementById('sampleText')
        var outputResult = document.getElementById('result')
        sampleTextarea.addEventListener('mouseup', function(){
            if (this.selectionStart != this.selectionEnd){ // check the user has selected some text inside field
                var selectedtext = this.value.substring(this.selectionStart, this.selectionEnd)
               output.innerHTML = selectedtext
            }
        }, false)
    
        </script>
    </html>
    

    These two properties returns the user's selected text from a form field, but it is especially useful where the indices of the selection isn't already known.

    For retrieving the textual part that the user has selected, you need to use window.getSelection(). This method is supported in all browsers. For example:-

    function slectedTxt(){
        var Text = ""
        if (window.getSelection){ // all modern browsers and IE9+
            Text = window.getSelection().toString();
        }
        return selectedText;
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: