Search code examples
javascriptgetelementbyid

How to select text on click input box in JavaScript?


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.


Solution

  • 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">