JSFiddle - React, Tailwind, and code Playground
HTML
Selection:
<br>
<textarea id="sel" rows="3" cols="50"></textarea>
<p>Please select some text.</p>
<input value="Some text in a text input">
<br>
<input type="search" value="Some text in a search input">
<br>
<input type="tel" value="4872349749823">
<br>
<input type="number" value="5">
<br>
<textarea>Some text in a textarea</textarea>
<p> </p>
<input type="password" value="test">
<br>
<input type="submit" value="Submit!">
<br>
<button>Don't know what to write.. :(</button>
JavaScript
function getSelectedText() {
var curElem = document.activeElement;
var fixElems = ['textarea', 'input'];
if (fixElems.indexOf(curElem.tagName.toLowerCase()) > -1) {
return curElem.value.substring(curElem.selectionStart, curElem.selectionEnd);
} else if (window.getSelection) {
return window.getSelection().toString();
} else {
return false;
}
}
document.onmouseup = document.onkeyup = document.onselectionchange = function() {
document.getElementById("sel").value = getSelectedText();
};