I'm trying to get the selected text inside an <input> when a button is clicked.
I'm successfully window.getSelection() to get selected text, but when I click a button, the input's focus and selected text are lost.
I know there are solutions for this -- I have seen a jQuery library or two -- but I am looking for a (hopefully simple) vanilla JS solution.
<p>Select some text then click the button (doesn't work)</p>
<input type="text" size="20" value="select something">
<button id="btn">alert selection</button>
<script>
document.getElementById('btn')
.addEventListener('click', function() {
alert(window.getSelection().toString());
});
</script>
<p>Select some text and see it alerted (works)</p>
<input id="input" type="text" size="20" value="select something">
<script>
document.getElementById('input')
.addEventListener('click', function() {
alert(window.getSelection().toString());
});
</script>
Edit
In reaction to the solutions posted below, one issue I need to avoid is previous selections effectively being cached. If the user deselects the text purposefully (not by clicking this specific button), I need it to not remember the old selection. The eventual goal is to modify the selected substring when the button is clicked, and if nothing is selected to just append to it.