How to get selected text from a textbox control with JavaScript
javascriptTo 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.
Other Article on Tag javascript
- - Adding and removing content in jQuery
- - Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
- - Can I change the Dojo namespace to something other than dojo
- - Can I prevent user pasting Javascript into Design Mode IFrame
- - dynamically create html element in javascript
- - Find XY of an HTML element with JavaScript
- - How can I upload files asynchronously with jQuery
- - How can you display Typing Speed using Javascript or the jQuery library
- - How do you capture mouse events in firefox
- - How to auto-size an iFrame