-
Retrieving the text contents and reading the selected portion of a field's value
over 9 years ago
over 9 years ago
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>
<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;
- }
function slectedTxt(){ var Text = "" if (window.getSelection){ // all modern browsers and IE9+ Text = window.getSelection().toString(); } return selectedText; }
Can you help out the community by solving one of the following Javascript problems?
Do activity (Answer, Blog) > Earn Rep Points > Improve Rank > Get more opportunities to work and get paid!
For more topics, questions and answers, please visit the Tech Q&A page.
0 Comment(s)