Auto select text in HTML input

13,738

Solution 1

AFAIK there is no default feature which highlight an input text when it's active in HTML. You will need to use some Javascript.

I can recommand you to check out this StackOverflow question which provides a simple and pretty efficient code:

<input type="text" name="textbox" value="Test" onclick="this.select()" />

N.B: In a UX point of view, highlight by default an input text on click can be a bad idea. If the user typed something and wants to modify his input, it will hightlight and he will need tu use the keyboard arrows to change the cursor position. Be carefull with this feature.

Solution 2

You could also do this with jQuery using document.ready if you wanted the box to always be selected.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<input type="text" name="textbox" id="textbox" value="Test" />
    <script>
    $(document).ready(function(){
	var autoselect = document.getElementById('textbox');
	autoselect.select();
      
    });
    </script>
Share:
13,738
Alex
Author by

Alex

Updated on June 08, 2022

Comments

  • Alex
    Alex almost 2 years

    I have an HTML input as follows:

    <input type="text" value="Link etc..." readOnly={true}/>
    

    I am trying to make the text inside the input to be auto highlighted at the point the input is displayed on the page.

    I have found lots of questions that show how to do this onClick etc, but none that highlight the text by default when the input displays.

    I am sure this is a simple task - but I cannot find the answer anywhere!!

    NOTE: I am sure I could work out how to achieve this by firing a JavaScript function on my page - but this seems a bit of overkill - I am trying to achieve this in the HTML declaration

    I am also using React - but I do not think this is relevant for this question?