JavaScript How to Get Selected Text from a Textbox

To get selected text from a textbox using JavaScript, you can use the following JavaScript code:

<script>
function show() {
  var text = document.getElementById("text");
  var selection = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);
  alert(selection);
}
</script>

<TEXTAREA id="text">Highlight this text or parts of it and click the button below!</TEXTAREA><BR>
<INPUT type="button" onclick="show()" value="Select text and click here" />

You can try the above code solution by highlighting some text from the textbox below and clicking the button. Then whatever you highlight will appear in the alert box that pops up when you click the button.




This creates a result like this:

JavaScript popup with OK

A Step-by-Step Breakdown

In the above example, you saw a simple HTML/JavaScript code that demonstrates how to retrieve (and show) the selected text from a text area on a web page.

In case you had a hard time understanding the code, make sure to read the line-by-line breakdown.

First, let’s take a look at the HTML part of the snippet.

<TEXTAREA id="text">Highlight this text or parts of it and click the button below!</TEXTAREA>

This creates a simple text area element with the ID attribute set to “text“. This text area consists of the text that you can later highlight and grab using JavaScript.

<INPUT type="button" onclick="show()" value="Select text and click here" />

This HTML creates a button element with an onclick attribute that calls the JavaScript show function when the button is clicked. The show function doesn’t exist yet, it’s defined further down below.

Next, let’s take a look at the JavaScript code line by line.

var text = document.getElementById("text");

This line retrieves the text area element from HTML by its ID and stores it in a variable.

var selection = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);

This piece of code retrieves the currently selected text from the text area element and assigns it to a variable called “selection”.

The selectionStart and selectionEnd properties of the text area element determine the start and end positions of the selected text.

The substr method extracts the selected text from the text area’s value.

alert(selection);

Last but not least, an alert box shows the highlighted text when you’ve clicked the button.

Scroll to Top