How to get selected text from a textbox control with JavaScript

javascript

To get the selected text from a textbox control using JavaScript, you can use the selectionStart and selectionEnd properties of the text input element.

Here’s an example code snippet:

<input type="text" id="myInput" value="Hello world!">

<button onclick="getSelectedText()">Get selected text</button>

<script>
function getSelectedText() {
  const input = document.getElementById('myInput');
  const start = input.selectionStart;
  const end = input.selectionEnd;
  const selectedText = input.value.substring(start, end);
  console.log(selectedText);
}
</script>

In this example, we first define a textbox input element with an id of myInput and a default value of Hello world!. We then define a button element with an onclick attribute that calls a getSelectedText() function when clicked.

Inside the getSelectedText() function, we first retrieve the textbox element using document.getElementById(). We then get the start and end positions of the selection using the selectionStart and selectionEnd properties of the textbox element. Finally, we extract the selected text from the textbox value using the substring() method and log it to the console.

When the button is clicked, the getSelectedText() function is called and the selected text from the textbox is logged to the console.

Note that this approach only works for text inputs and not for other types of form elements such as checkboxes or radio buttons.