0

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.

4
  • Hopefully someone understands what you means because I have no idea what you are asking for. Commented 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 menu Commented Mar 5, 2020 at 15:46
  • Refer to: stackoverflow.com/questions/4067469/… Commented Mar 5, 2020 at 15:46
  • 1
    Does this answer your question? Selecting all text in HTML text input when clicked Commented Mar 5, 2020 at 15:47

2 Answers 2

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">
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.