I wrote a cross-browser function to get the text selected in a text box or text input, and after some hints and endings of the final version, I consider it to be the best I've seen. Several times I published it on Stack Overflow. Here is one example: Is there an Internet Explorer approved option for selectStart and selectionEnd?
To determine when a user makes a selection in a text field, you can use the select event:
var textarea = document.getElementById("some_id"); textarea.onselect = function() { var selection = getInputSelection(textarea); var selectedText = textarea.value.slice(selection.start, selection.end); console.log("Selected text: " + selectedText); };
source share