Asked 7 years ago
31 Jan 2017
Views 11974
yogi

yogi posted

How to get selected text of Textarea in JavaScript ?

How to get selected text of Textarea in JavaScript ?


<textarea id="editor">Hi , how to get selected Text of textarea(html) in JavaScript ?</textarea>


suppose i select "Text of textarea(html) " in textarea than it should be give result that selected text in JavaScript or jQuery


var selectedText=document.getElementById("editor").getSelectedText();


is there any getSelectedText() function in JavaScript or jQuery , which return me only selected text , not whole text of textarea ?
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00


	var idoftextarea='answer';
	function getSelectedText(idoftextarea){
		var textArea = document.getElementById(idoftextarea);
		var text =textArea.value;
		var indexStart=textArea.selectionStart;
		var indexEnd=textArea.selectionEnd;
		alert(text.substring(indexStart, indexEnd));
	 
	}
 

	getSelectedText(idoftextarea);



let me explain how it work ?
when you do document.getElementById(idoftextarea); it return object of textarea Element, which id we passed on the getElementById

textarea object have property selectionStart and selectionEnd

selectionStart
which say from where selection start , its integer value

selectionEnd
which say from where selection end, its integer value

so substring function will give us string from given starting point to other

text.substring(indexStart, indexEnd) give us text of starting point of selection to end

For Your Info(FYI)

Prior to Firefox 51 , Firefox returned 0 as the value of both HTMLTextAreaElement.selectionStart and HTMLTextAreaElement.selectionEnd. Starting in Firefox 51, it correctly returns the offset of the character following the current position of the text input cursor.

Post Answer