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.
-
Hopefully someone understands what you means because I have no idea what you are asking for.epascarello– epascarello2020-03-05 15:40:17 +00:00Commented Mar 5, 2020 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 menuM. Rogers– M. Rogers2020-03-05 15:46:16 +00:00Commented Mar 5, 2020 at 15:46
-
Refer to: stackoverflow.com/questions/4067469/…Martin– Martin2020-03-05 15:46:57 +00:00Commented Mar 5, 2020 at 15:46
-
1Does this answer your question? Selecting all text in HTML text input when clickedMartin– Martin2020-03-05 15:47:42 +00:00Commented Mar 5, 2020 at 15:47
Add a comment
|
2 Answers
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">
Comments
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>