How to Get the Selected Text in a Textarea

How can I get the selected text in a textarea?

Try the jquery-fieldselection plugin.

You can download it from here. There is an example too.

HTML5 how to get selected text out of a textarea

Following is simple way to get selected text of textarea of html. Still not clear what you want as following method simply will give you selected text in alert.

<html><head>
<script>
function alertme(){
var textarea = document.getElementById("textArea");
var selection = (textarea.value).substring(textarea.selectionStart,textarea.selectionEnd);
alert (selection);
}

</script>

</head>
<body>
<p><textarea class="noscrollbars" id="textArea"></textarea></p>
<button onclick="alertme()">Click me</button>
</body></html>

When you select text, the button will alert you what you have selected. selectionStart gives you starting point and selectionEnd gives you end point, while substring needs three arguments string, starting point and ending point.

How to get highlighted text position from textarea?

This will work for text selection with the mouse and keyboard for all <textarea> elements on the page.
Change the selector (be more specific) if you don't want all <textarea> elements to have this text selection.

Read the comments, you will find out there how to disable keyboard selection, if you don't want/need keyboard selection.

var mySelection = function (element) {
let startPos = element.selectionStart;
let endPos = element.selectionEnd;
let selectedText = element.value.substring(startPos, endPos);

if(selectedText.length <= 0) {
return; // stop here if selection length is <= 0
}

// log the selection
console.log("startPos: " + startPos, " | endPos: " + endPos );
console.log("selectedText: " + selectedText);

};

var textAreaElements = document.querySelectorAll('textarea');
[...textAreaElements].forEach(function(element) {
// register "mouseup" event for the mouse
element.addEventListener('mouseup', function(){
mySelection(element)
});

// register "keyup" event for the keyboard
element.addEventListener('keyup', function( event ) {
// assuming we need CTRL, SHIFT or CMD key to select text
// only listen for those keyup events
if(event.keyCode == 16 || event.keyCode == 17 || event.metaKey) {
mySelection(element)
}
});
});
textarea {
resize: none;
width: 50%;
height: 50px;
margin: 1rem auto;
}
<textarea>I am a student and I want to become a good person</textarea>

How to get the selected text from text area in react?

Yes there is a method to do this, specially in React. The way you should go to achieve this is as follow.

step 1:- use ref in your textarea ui element. like

     `<textarea
className='html-editor'
ref='myTextarea'
value = {this.state.textareaVal}
onChange={(event)=>{
this.setState({
textareaVal:event.target.value;
});
}}
>
</textarea>`

step 2:- now you can access the DOM element,using react refs.

    let textVal = this.refs.myTextarea; 

step 3:- use selectionStart and selectionEnd :- using selectionStart and

selectionEnd you can get to know your start and end pointer

of selected text.which can be done as below;

        let cursorStart = textVal.selectionStart;
let cursorEnd = textVal.selectionEnd;

now you have start and end index of your selected text.

step 4 :- use javascript substring function to get the selected text.

    this.state.textareaVal.substring(cursorStart,cursorEnd) 

How to get text value of selected text from onSelect DOM event

to grab the selected text you can use textarea.selectionStart and textarea.selectionEnd as mentioned in another answer

To solve second part of the question you will need some CSS rule to highlight the selected text. please check the code snippet.

let text_selection = document.getElementById("text");
text_selection.addEventListener("select", highlightText);

function highlightText() {
let textarea = event.target;
let selection = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
console.log(selection)
}
::-moz-selection {
color: yellow;
}

::selection {
color: yellow;
}
<textarea id="text">
Text to be highlighted
</textarea>

How to get range of selected text of textarea in JavaScript

Use the code below or check this fiddle

   function getTextSelection(el) {
var start = 0, end = 0, normalizedValue, range,
textInputRange, len, endRange;

if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
start = el.selectionStart;
end = el.selectionEnd;
} else {
range = document.selection.createRange();

if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");

// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());

// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);

if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;

if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}
alert("start :" + start + " End :" + end);
}

How to get this selected text into DIV instead of textarea, and also collect one by one all selected part into div

as per what i understand that you need to append the selection text to a new element

here we go , check out the snippet

// Function to get the Selected Text  
function getSelectedText() {
var selectedText = '';
// #### create a new element with variable (nw) #### //
var nw = document.createElement("div"); // Element's tag
nw.className = "NEWCLASS"; // Element's class name
nw.style.textAlign = "center"; // some applied style

// window.getSelection
if (window.getSelection) {
selectedText = window.getSelection();
}
// document.getSelection
else if (document.getSelection) {
selectedText = document.getSelection();
}
// document.selection
else if (document.selection) {
selectedText =
document.selection.createRange().text;
} else return;
// #### get the Selected text appended to body #### //
nw.innerHTML = selectedText;
document.body.appendChild(nw); // Append element to body

}
<p>Select any part of this sentence and press the button. Select any part of this sentence and press the button. Select any part of this sentence and press the button</p>

<br>

<input type="button" value="Get Selection" onmousedown="getSelectedText()">


Related Topics



Leave a reply



Submit