How to get selected text from a textbox using JavaScript?

By IncludeHelp Last updated : November 08, 2023

To get the selected text from a textbox you, use the JavaScript's Web UPI method window.getSelection(). This method returns the text selected by the user.




In this example, we have a textbox and, on the button's onclick event, we will get and display the selected text in a paragraph (HTML's <p> tag).

<!DOCTYPE html>
    <h1>Example: How to Get Selected Text from a Textbox using JavaScript?</h1>
    <input type="text" id="inputText"/>
    <button onclick="showSelectedText()">Get selected text</button>
    <p id="displayText"></p>
    <script type="text/javascript">
      function showSelectedText(){
      	result = window.getSelection();
      	document.getElementById("displayText").innerHTML = result;


The output of the above code is:

Output: Get selected text from a textbox using JavaScript

JavaScript Examples »

Comments and Discussions!

Copyright © 2023 All rights reserved.