how to auto select an input field and the text in it on page load

Viewed 161236

Upon page load I want to move the cursor to a particular field. No problem. But I also need to select and highlight the default value that is placed in that text field.

10 Answers

To do it on page load:

window.onload = function () {
  var input = document.getElementById('myTextInput');
  input.focus();
  input.select();
}
<input id="myTextInput" value="Hello world!" />

In your input tag use autofocus like this

<input type="text" autofocus>

    var input = document.getElementById('myTextInput');
    input.focus();
    input.setSelectionRange( 6,  19 );
    <input id="myTextInput" value="Hello default value world!" />

select particular text on textfield

Also you can use like

input.selectionStart = 6;
input.selectionEnd = 19;

Using the autofocus attribute works well with text input and checkboxes.

<input type="text" name="foo" value="boo" autofocus="autofocus"> FooBoo
<input type="checkbox" name="foo" value="boo" autofocus="autofocus"> FooBoo
Related