I am new to JavaScript and building an application in which, using plain JavaScript, I would like to select the text (similar to right clicking and select all) upon click of an element on a web page if the element is of type input. Can this be done? If so how would I go about doing this. Any info would be appreciated.
Asked
Active
Viewed 1,283 times
0
-
Hopefully someone understands what you means because I have no idea what you are asking for. – epascarello Mar 05 '20 at 15:40
-
I'm looking for the JavaScript, for when I click on any element in an HTML document, if the clicked on element is a text input box, I can simulate right clicking on that element and click "select all" from the context menu – M. Rogers Mar 05 '20 at 15:46
-
Refer to: https://stackoverflow.com/questions/4067469/selecting-all-text-in-html-text-input-when-clicked – Martin Mar 05 '20 at 15:46
-
1Does this answer your question? [Selecting all text in HTML text input when clicked](https://stackoverflow.com/questions/4067469/selecting-all-text-in-html-text-input-when-clicked) – Martin Mar 05 '20 at 15:47
2 Answers
1
You can add this script at the bottom of your body tag
<script>
document.querySelectorAll('.js-select-input').forEach(input => {
input.addEventListener('click', (e) => e.currentTarget.select())
})
</script>
and for every input that you would like to have this autoselect functionality add the class "js-select-input" as in this example:
<input class="js-select-input" value="foo">

Andrei Cristea
- 141
- 1
- 4
1
Use select
method to achieve this.
Use select
method in the callback function of input's onfocus
event.
For better understanding, see the following example:
function testFunc(focusedInput) {
focusedInput.select();
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="test-input" type="text" name="test-input" value="default-value" onfocus="testFunc(this)">
<script>
function testFunc(focusedInput) {
focusedInput.select();
}
</script>
</body>
</html>

moeinghasemi
- 81
- 1
- 10