A reliable way to select all text in a text field

I am trying to ensure that the content of the HTML text box is fully selected by onFocus.

I know a simple solution for placing onfocus="this.select()"on a component, but this is not a good solution, because if a user double-clicks on an area, then the choice is lost, and in browsers such as chrome, it rarely works as it should, and simply returns to form input.

I searched on Google for a while and cannot find a good solution, most of the suggestions are for this simple solution.

I would like the selection inside the text box not to change after it is selected, and if possible, the user should not edit the text in the text box, for example, if you used AdSense when you grab the code from AdSense, the selection never changes, and you cannot change the code in the text box.

Any solutions would be appreciated.

+3
source share
3 answers

I modified the Tim Down code to work as it should, here is the final code for other people (make sure you use O in readOnly ) ..

<script type="text/javascript">
    function selectAll(id) {
        var textBox = document.getElementById(id);
        textBox.select();
        textBox.readOnly = true;
        textBox.onmouseup = function() {
            textBox.select();
            return false;
        };
        textBox.onmousedown = function() {
            textBox.select();
            return false;
        };
    };
</script>
+3
source

, , . , - : , . , , :

<input type="text" id="foo" readonly value="Some text">

<script type="text/javascript">
    var textBox = document.getElementById("foo");
    textBox.onfocus = function() {
        textBox.select();

        // Work around Chrome little problem
        textBox.onmouseup = function() {
            // Prevent further mouseup intervention
            textBox.onmouseup = null;
            return false;
        };
    };
</script>
+6
<html>
<body>
<script>
function getElement(elemname)
{
 if (document.getElementById)
  return document.getElementById(elemname);
 else if (document.all)
  return document.all[elemname];
 return 0;
}
function lockingSelect()
{
 ta = getElement("mytext");
 ta.select();
 ta.readonly = true;

}
</script>


<textarea id = "mytext"></textarea>

<br>
<input type=button onclick="lockingSelect();" value="lock"/>
</body>

</html>
0
source

Source: https://habr.com/ru/post/1782879/


All Articles